package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
    "encoding/hex"
    "crypto/md5"
    "html/template"
	"net/http"
    "math/rand"
	"strings"
	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
	"bytes"
	"sync"
    "time"
    "sort"
    "strconv"
    "log"
    "os"
    "html"
    "golang.org/x/time/rate"
    "path/filepath"
    "regexp"
    "math"
    "github.com/google/uuid"
    "github.com/gorilla/websocket"
    "github.com/gin-contrib/sessions"
    "encoding/base64"
    "github.com/gin-contrib/sessions/cookie"
    "github.com/wechatpay-apiv3/wechatpay-go/core"
    "github.com/wechatpay-apiv3/wechatpay-go/core/notify"
    "github.com/wechatpay-apiv3/wechatpay-go/core/option"
    "github.com/wechatpay-apiv3/wechatpay-go/utils"
    "github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
    "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
    "crypto"
    cryptorand "crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
    "crypto/x509"
    "context"
    "golang.org/x/crypto/bcrypt"
    "github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
)
type ExtendedOrder struct {
    Order
    Source string `json:"source"` // 新字段标记订单来源（网站或AI群）
}

// 消息板结构体定义（与文档中的Message不同）
type MessageBoard struct {
    Username   string `json:"username"`
    Content    string `json:"content"`
    AvatarPath string `json:"avatar_path"`
    CreatedAt  string `json:"created_at"`
}
type Withdrawal struct {
	ID        string  `db:"id"         json:"id"`
	OpenID    string  `db:"openid"     json:"openid"`
	NickName  string  `db:"nickname"   json:"nickname"`
	QRUrl     string  `db:"qr_url"     json:"qrUrl"`
	Amount    float64 `db:"amount"     json:"amount"`
	Status    string  `db:"status"     json:"status"`   // pending / done / reject
	CreateAt  string  `db:"create_at"  json:"createTime"`
	AuditorID int64   `db:"auditor_id" json:"-"`
}
// 请求结构体
type BlacklistRequest struct {
    Nickname string `json:"nickname" binding:"required"`
    Reason   string `json:"reason"`
}

type ReportRequest struct {
    Nickname string `json:"nickname" binding:"required"`
    Reason   string `json:"reason" binding:"required"`
}
type ConversationItem struct {
	ID            string    `json:"ID"`
	GroupID       string    `json:"GroupID"`
	GroupName     string    `json:"GroupName"`
	GroupUserNickName string `json:"GroupUserNickName"`
	WeChatUser    string    `json:"WeChatUser"`
	Msg           string    `json:"Msg"`
	OrderType     string    `json:"OrderType"`
	CreatedAt     time.Time `json:"CreatedAt"`
	IsActive      bool      `json:"IsActive"`
	IsCompleted   bool      `json:"IsCompleted"`
}
// QRCodeRequest 小程序码请求参数
type QRCodeRequest struct {
	GuaranteeID string `json:"guaranteeId" binding:"required"`
	Page        string `json:"page"`
	Scene       string `json:"scene" binding:"required"`
}

// QRCodeResponse 小程序码响应
type QRCodeResponse struct {
	Code     int    `json:"code"`
	Message  string `json:"message"`
	ImageURL string `json:"imageUrl,omitempty"`
}
const (
	StatusCreated     = "created"      // 已创建
	StatusWaitingJoin = "waiting_join" // 等待加入
	StatusProcessing  = "processing"   // 进行中
	StatusCompleted   = "completed"    // 已完成
	StatusCancelled   = "cancelled"    // 已取消
)

// 担保系统角色枚举
const (
	RoleWorker = "worker" // 打手
	RoleBoss   = "boss"   // 老板
)
type Client struct {
    conn     *websocket.Conn
    role     string
    orderID  string
    username string
}

// 消息结构体
type Message struct {
	OrderID   string `json:"order_id"`
	Content   string `json:"content"`
	Sender    string `json:"sender"` // "buyer" 或 "seller"
	CreatedAt int64  `json:"created_at"`
}
type Task struct {
    ID       string   `json:"id"` // 唯一时间戳
    Interval int      `json:"interval"`
    Status   int      `json:"status"` // 0: 未开始, 1: 添加中, 2: 已完成
    GroupIDs []string `json:"group_ids"` // 指定发送的群组ID
}
// 辅助函数：检查 NullFloat64 是否为空，为空则返回默认值
func ifNullFloat64(nf sql.NullFloat64, defaultValue float64) float64 {
    if nf.Valid {
        return nf.Float64
    }
    return defaultValue
}
// 辅助函数：检查 NullInt64 是否为空，为空则返回默认值
func ifNullInt64(ni sql.NullInt64, defaultValue int64) int64 {
    if ni.Valid {
        return ni.Int64
    }
    return defaultValue
}
type BridgeInfo struct {
    ID         string
    Info         template.HTML
    TotalPayment int
    WeChatUser string // 根据之前讨论，这个字段是为了处理图片路径
}

type FlexibleOrder struct {
    OrderDetails          []string `json:"orderDetails"`
    RestrictedOrderDetails []string `json:"restrictedOrderDetails"` // New field for restricted order details
    SelfOrder             bool     `json:"selfOrder"`
    Friend                string   `json:"friend"`
    Stop                  bool     `json:"stop"`
}
// 辅助函数比较两个订单详细信息是否相同
func equal(a, b []string) bool {
    if len(a) != len(b) {
        return false
    }
    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}
type rechargeRequest struct {
    Amount int `json:"amount"`
}
type CancelRequestBody struct {
    Code string `json:"code"`
}
type TemplateMessage struct {
    Touser     string                   `json:"touser"`
    TemplateID string                   `json:"template_id"`
    URL        string                   `json:"url,omitempty"`
    Data       map[string]TemplateData  `json:"data"`
    MiniProgram map[string]interface{}  `json:"miniprogram,omitempty"`
}
type OpenIDResponse struct {
	OpenID string `json:"openid"`
    ErrMsg string `json:"errmsg,omitempty"`
}
type TradeItem struct {
    ID             int    
    Seller         string 
    Buyers         string  
    ItemName       string  
    Description    string  
    Price          float64 
    Quantity       int    
    ImageFileName  string  
}

type TemplateData struct {
    Value string `json:"value"`
    Color string `json:"color,omitempty"`
}
// 定义结构体
type Playmate struct {
    ID string
    PlaymateID int
    ImagePath  string
    FilePath   string
    Text       string
    Price      int
}
type Bridge struct {
    ID                string
    GroupID           string
    GroupName         string
    GroupUserNickName string
    WeChatUser        string
    IsActive          bool
    IsCompleted       bool
    Msg               string
    GameID            string
    Stars             int
    StarCost          int
    OrderType         string
    CreatedAt         time.Time
    LastMessageTime   time.Time
    FinalRank         sql.NullString
    WeChatUsername    sql.NullString  // 改为 sql.NullString
}
type Order struct {
    ID                string         `json:"id"`
    GroupID           string         `json:"group_id"`
    GroupName         string         `json:"group_name"`
    GroupUserNickName string         `json:"group_user_nick_name"`
    WeChatUser        string         `json:"we_chat_user"`
    IsActive          bool           `json:"is_active"`
    IsCompleted       bool           `json:"is_completed"`
    Msg               string         `json:"msg"`
    GameID            sql.NullString `json:"game_id"`
    Stars             sql.NullInt64  `json:"stars"`
    StarCost          sql.NullInt64  `json:"star_cost"`
    OrderType         string         `json:"order_type"`
    CreatedAt         time.Time      `json:"created_at"`
    LastMessageTime   time.Time      `json:"last_message_time"`
    FinalRank         sql.NullString `json:"final_rank"`
    WeChatUsername    sql.NullString `json:"we_chat_username"` // 改为 sql.NullString
}

type sender struct {
    NickName string
    UserName string
}
// 定义一个结构体来存储群的状态
type GroupState struct {
    IsOrderMode   bool
    IsOrderMode2  bool
    IsOrderMode3  bool
    IsOrderMode4  bool
}
// 定义数据结构
type FriendData struct {
	API       int    `json:"api"`
	WeChat    string `json:"wechat"`
	Port      int    `json:"port"`
	PID       int    `json:"pid"`
	Msg       string `json:"msg"`
	ErrorCode int    `json:"errorCode"`
	ErrorMsg  string `json:"errorMsg"`
	Data      struct {
		Record []Record `json:"record"`
	} `json:"data"`
}
type Announcement struct {
	ID        int    `json:"id"`
	Message   string `json:"message"`
	CreatedAt string `json:"created_at"`
}
type Transfer struct {
	API  int    `json:"api"`
	Data struct {
		TransferID string `json:"transferid"`
		UserName   string `json:"userName"`
	} `json:"data"`
}
type Record struct {
	UserName      string `json:"userName"`
	NickName      string `json:"nickName"`
	Remark        string `json:"remark"`
	BigHeadImgUrl string `json:"bigHeadImgUrl"`
	Type          string `json:"type"`
}

// 调整后的 CallbackData 和 Data 结构体
type CallbackData struct {
	API       int    `json:"api"`
	WeChat    string `json:"wechat"`
	Port      int    `json:"port"`
	PID       int    `json:"pid"`
	Msg       string `json:"msg"`
	ErrorCode int    `json:"errorCode"`
	ErrorMsg  string `json:"errorMsg"`
	Data      Data   `json:"data"`
}
type PaymentData struct {
	BridgeID  string `json:"bridge_id"`
	Payment   int    `json:"payment"`
	Debtor    string `json:"debtor"`
	Creditor  string `json:"creditor"`
	CreatedAt string `json:"created_at"`
}
type Data struct {
	EncryptUserName string `json:"encryptUserName"` // 好友添加消息中的用户名
	Ticket          string `json:"ticket"`         // 好友添加消息中的 ticket
	SortIndex       int64      `json:"sortIndex"`        // 消息排序索引
	LocalID         int        `json:"localId"`         // 本地 ID
	MsgPrefixID     string     `json:"msgPrefixId"`     // 消息前缀 ID
	MsgSvrID        string     `json:"msgSvrID"`        // 消息服务端 ID
	UserName        string     `json:"userName"`        // 发送者用户名
	NickName        string     `json:"nickName"`        // 发送者昵称
	StrContent      string     `json:"strContent"`      // 消息内容
    Content           string     `json:"content"`         // XML消息内容
	MsgSource       string     `json:"msgSource"`       // 消息源信息 (XML 格式)
	CreateTime      int        `json:"createTime"`      // 创建时间 (时间戳)
	Type            int        `json:"type"`            // 消息类型
	SubType         int        `json:"subType"`         // 消息子类型
	IsSender        int        `json:"isSender"`        // 是否为发送者
	BytesExtra      BytesExtra `json:"bytesExtra"`      // 扩展字段
	TypeInfo        string     `json:"typeInfo"`        // 类型信息
	SmallHeadImgUrl string     `json:"smallHeadImgUrl"` // 小头像 URL
	BigHeadImgUrl   string     `json:"bigHeadImgUrl"`   // 大头像 URL
	IsBizMsg        int        `json:"isBizMsg"`        // 是否为企业消息
	Chatroomusername    string      `json:"chatroomusername`  
}

type BytesExtra struct {
	UserName        string `json:"userName"`        // 用户名
	Thumb           string `json:"thumb"`          // 缩略图
	Image           string `json:"image"`          // 图片
	File            string `json:"file"`           // 文件
	RoomNick        string `json:"roomNick"`       // 群昵称
	NickName        string `json:"nickName"`       // 用户昵称
	SmallHeadImgUrl string `json:"smallHeadImgUrl"`// 小头像 URL
	BigHeadImgUrl   string `json:"bigHeadImgUrl"`  // 大头像 URL
	AtUserList      []string `json:"atuserlist"`   // @用户列表
}

type RankTracking struct {
    StarredUser     string
    WaitingFor      sql.NullString // 修改为可处理NULL值的类型
    OrderType       string
    Rank            string
    Position        string
    Direction       string
    GroupChatActive bool
    Active          bool
}

// 定义 POST 请求结构
type AddFriendRequest struct {
	API  int       `json:"api"`
	Data FriendPostData `json:"data"`
}

type FriendPostData struct {
	EncryptUserName string `json:"encryptUserName"`
	Ticket          string `json:"ticket"`
	scene           int    `json:"scene"`
	rights          int    `json:"rights"`
}

const (
	appID     = "wxc3e5d26b9435ac5e"
	appSecret = "0e5e24c645666daf45628095363d7d04"
    orderModeImage = "./image/gs.jpg"
    orderModeImage2 = "./image/peizhi/mp.jpg"
)
var previousWindowState string
var (
    globalMessageContactMap = make(map[string]string)
    balanceClients    = make(map[string]map[*websocket.Conn]bool) // openid -> 连接 -> true
    balanceClientsMux = sync.RWMutex{}
	externalGroups = struct {
		sync.RWMutex
		groups map[string]bool
	}{groups: make(map[string]bool)}
    detectionTarget struct {
        sync.RWMutex
        groupKey    string
        roomNick    string
        contentHash [16]byte
        count       int
        window      int64
    }
    limiter = rate.NewLimiter(rate.Limit(10), 10)
    lastSent time.Time     // 上次请求时间
    sendMu   sync.Mutex    // 互斥锁
    tasks []Task
    orders []FlexibleOrder
    upgrader = websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
        CheckOrigin: func(r *http.Request) bool {
            return true // 允许来自任何源的连接
        },
    }
    mu     sync.Mutex
    newmultipleMatches int
    groupStates = make(map[string]*GroupState)
	db *sql.DB
	mapMutex sync.Mutex
	lastActiveUserMap = make(map[string]string)
    isInternalOrderMode bool = false // 默认为外部接单模式
    pendingImages map[string]string = make(map[string]string)
    isBridgeForwardingEnabled bool = true // 默认启动桥梁转发定时任务
    clientsMutex sync.RWMutex
    clients = make(map[string]map[*websocket.Conn]Client)
	mutex   = &sync.RWMutex{}
    currentTracking *RankTracking
    globalGameIDMap = make(map[string]string)
    db2 *sql.DB
    addPlaymateMode = false
    currentPlaymateID int
)
// 辅助函数：检查 NullString 是否为空，为空则返回默认值
func ifNullString(ns sql.NullString, defaultValue string) string {
    if ns.Valid {
        return ns.String
    }
    return defaultValue
}
func initializeDatabase() error {
    var err error // Declare error variable to use it globally in this function
    if _, err = os.Stat("static/qrcodes"); os.IsNotExist(err) {
		if err = os.MkdirAll("static/qrcodes", 0755); err != nil {
			log.Fatalf("[FATAL] 创建小程序码存储目录失败: %v", err)
		}
	}
    db, err = sql.Open("sqlite3", "./star_journal.db")
    if err != nil {
        fmt.Printf("Error opening database: %v\n", err)
        return err
    }
    // 初始化副数据库（db2）
    db2, err = sql.Open("sqlite3", "./data.db")
    if err != nil {
        return fmt.Errorf("failed to open secondary database: %w", err)
    }
	createCurrentEventTableSQL := `CREATE TABLE IF NOT EXISTS current_event (
        id INTEGER PRIMARY KEY,
        event_title TEXT, 
        event_text TEXT
    );`
    _, err = db.Exec(createCurrentEventTableSQL)
    if err != nil {
        fmt.Printf("Error creating current_event table: %v\n", err)
        return err
    }     
	createBridgesTableSQL := `CREATE TABLE IF NOT EXISTS Bridges (
        ID TEXT PRIMARY KEY,
        GroupID TEXT NOT NULL,
        GroupName TEXT NOT NULL,
        GroupUserNickName TEXT NOT NULL,
        WeChatUser TEXT,
        IsActive BOOLEAN,
        IsCompleted BOOLEAN,
        Msg TEXT,
        GameID TEXT,
        Stars INTEGER,
        StarCost INTEGER,
        OrderType TEXT,
        CreatedAt TIMESTAMP,
        LastMessageTime TIMESTAMP,
        FinalRank TEXT  
    );`    
    _, err = db.Exec(createBridgesTableSQL)
    if err != nil {
        fmt.Printf("Error creating bridges table: %v\n", err)
        return err
    }
    // 添加用户余额字段
    alterUsersTableSQL := `ALTER TABLE users ADD COLUMN balance DECIMAL(10,2) DEFAULT 0.00;`
    _, err = db.Exec(alterUsersTableSQL)
    if err != nil {
        // 如果列已经存在，SQLite会报错，但可以忽略
        fmt.Printf("Note: Users table balance column may already exist: %v\n", err)
    }
    
    // 创建退款记录表
    createRefundsTableSQL := `CREATE TABLE IF NOT EXISTS Refunds (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        OutRefundNo VARCHAR(32) NOT NULL,
        TransactionID VARCHAR(32) NOT NULL,
        OutTradeNo VARCHAR(32) NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        Reason TEXT,
        Status VARCHAR(20) NOT NULL,
        CreateTime DATETIME NOT NULL,
        UpdateTime DATETIME,
        UNIQUE(OutRefundNo)
    );`
    _, err = db.Exec(createRefundsTableSQL)
    if err != nil {
        fmt.Printf("Error creating Refunds table: %v\n", err)
        return err
    }
    
    // 创建退款失败记录表
    createRefundFailuresTableSQL := `CREATE TABLE IF NOT EXISTS RefundFailures (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        TransactionID VARCHAR(32) NOT NULL,
        OutTradeNo VARCHAR(32) NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        Reason TEXT,
        ErrorMessage TEXT,
        CreateTime DATETIME NOT NULL,
        RetryCount INTEGER DEFAULT 0,
        LastRetryTime DATETIME,
        Resolved INTEGER DEFAULT 0
    );`
    _, err = db.Exec(createRefundFailuresTableSQL)
    if err != nil {
        fmt.Printf("Error creating RefundFailures table: %v\n", err)
        return err
    }
    // 创建用户交易表
    createUserTransactionsTableSQL := `CREATE TABLE IF NOT EXISTS UserTransactions (
        ID TEXT PRIMARY KEY,
        OpenID TEXT NOT NULL,
        TransactionType TEXT NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        ServiceFee DECIMAL(10,2) DEFAULT 0.00,
        ActualAmount DECIMAL(10,2) NOT NULL,
        Status TEXT NOT NULL,
        RelatedOrderID TEXT,
        TransactionID TEXT,
        CreateTime DATETIME NOT NULL
    );`
    _, err = db.Exec(createUserTransactionsTableSQL)
    if err != nil {
        fmt.Printf("Error creating UserTransactions table: %v\n", err)
        return err
    }
    
    // 创建用户服务费表
    createUserFeesTableSQL := `CREATE TABLE IF NOT EXISTS UserFees (
        ID TEXT PRIMARY KEY,
        OpenID TEXT NOT NULL,
        FeeType TEXT NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        RelatedTransactionID TEXT,
        CreateTime DATETIME NOT NULL
    );`
    _, err = db.Exec(createUserFeesTableSQL)
    if err != nil {
        fmt.Printf("Error creating UserFees table: %v\n", err)
        return err
    }
    
    // 创建服务费记录表
    createServiceFeesTableSQL := `CREATE TABLE IF NOT EXISTS ServiceFees (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        TransactionID TEXT,
        WithdrawID TEXT,
        GuaranteeID TEXT,
        Type TEXT NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        CreateTime DATETIME NOT NULL
    );`
    _, err = db.Exec(createServiceFeesTableSQL)
    if err != nil {
        fmt.Printf("Error creating ServiceFees table: %v\n", err)
        return err
    }
    
    // 创建担保支付记录表
    createGuaranteePaymentsTableSQL := `CREATE TABLE IF NOT EXISTS GuaranteePayments (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        GuaranteeID TEXT NOT NULL,
        OpenID TEXT NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        ServiceFee DECIMAL(10,2) DEFAULT 0.00,
        TradeType TEXT NOT NULL,
        OutTradeNo TEXT NOT NULL,
        PrepayID TEXT,
        TransactionID TEXT,
        Status TEXT NOT NULL,
        CreateTime DATETIME NOT NULL,
        PayTime DATETIME
    );`
    _, err = db.Exec(createGuaranteePaymentsTableSQL)
    if err != nil {
        fmt.Printf("Error creating GuaranteePayments table: %v\n", err)
        return err
    }
    
    // 创建提现支付记录表
    createWithdrawPaymentsTableSQL := `CREATE TABLE IF NOT EXISTS WithdrawPayments (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        WithdrawID TEXT NOT NULL,
        OpenID TEXT NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        ServiceFee DECIMAL(10,2) DEFAULT 0.00,
        OutTradeNo TEXT NOT NULL,
        TransactionID TEXT,
        Status TEXT NOT NULL,
        CreateTime DATETIME NOT NULL,
        PayTime DATETIME
    );`
    _, err = db.Exec(createWithdrawPaymentsTableSQL)
    if err != nil {
        fmt.Printf("Error creating WithdrawPayments table: %v\n", err)
        return err
    }
    
    // 创建担保退款记录表
    createGuaranteeRefundsTableSQL := `CREATE TABLE IF NOT EXISTS GuaranteeRefunds (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        GuaranteeID TEXT NOT NULL,
        OutRefundNo TEXT NOT NULL,
        TransactionID TEXT NOT NULL,
        OutTradeNo TEXT NOT NULL,
        RefundAmount DECIMAL(10,2) NOT NULL,
        Reason TEXT,
        Status TEXT NOT NULL,
        CreateTime DATETIME NOT NULL,
        UpdateTime DATETIME
    );`
    _, err = db.Exec(createGuaranteeRefundsTableSQL)
    if err != nil {
        fmt.Printf("Error creating GuaranteeRefunds table: %v\n", err)
        return err
    }
    
    // 创建提现记录日志表
    createWithdrawLogsTableSQL := `CREATE TABLE IF NOT EXISTS WithdrawLogs (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,
        WithdrawID TEXT NOT NULL,
        Action TEXT NOT NULL,
        Amount DECIMAL(10,2),
        ServiceFee DECIMAL(10,2) DEFAULT 0.00,
        OperatorID TEXT,
        CreateTime DATETIME NOT NULL,
        Remark TEXT
    );`
    _, err = db.Exec(createWithdrawLogsTableSQL)
    if err != nil {
        fmt.Printf("Error creating WithdrawLogs table: %v\n", err)
        return err
    }
    // 添加绑定码表 - 用于存储绑定码与OpenID的关系
    createBindCodesTableSQL := `CREATE TABLE IF NOT EXISTS BindCodes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        openid TEXT NOT NULL,
        code TEXT NOT NULL UNIQUE,
        used INTEGER DEFAULT 0 NOT NULL, -- 0:未使用 1:已使用
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE(openid, code)
    );`
    _, err = db.Exec(createBindCodesTableSQL)
    if err != nil {
        return fmt.Errorf("error creating BindCodes table: %w", err)
    }
    
    // 创建索引
    createIndexesSQL := []string{
        `CREATE INDEX IF NOT EXISTS idx_bindcodes_code ON BindCodes(code);`,
        `CREATE INDEX IF NOT EXISTS idx_bindcodes_openid ON BindCodes(openid);`,
        `CREATE INDEX IF NOT EXISTS idx_users_openid ON users(openid);`,
    }
    
    for _, indexSQL := range createIndexesSQL {
        _, err = db.Exec(indexSQL)
        if err != nil {
            return fmt.Errorf("error creating index: %w", err)
        }
    }
    // 添加临时担保订单表 - 用于先支付后创建担保的流程
    createTempGuaranteesTableSQL := `CREATE TABLE IF NOT EXISTS TempGuarantees (
        ID VARCHAR(32) PRIMARY KEY,
        OpenID VARCHAR(64) NOT NULL,
        Deposit DECIMAL(10,2) NOT NULL,
        Amount DECIMAL(10,2) NOT NULL,
        Role VARCHAR(10) NOT NULL,
        Remark TEXT,
        OutTradeNo VARCHAR(32),
        PrepayID VARCHAR(64),
        CreateTime DATETIME NOT NULL,
        PayStatus VARCHAR(20) DEFAULT 'pending'
    );`
    _, err = db.Exec(createTempGuaranteesTableSQL)
    if err != nil {
        return fmt.Errorf("error creating TempGuarantees table: %w", err)
    }
    
    createGuaranteesTableSQL := `CREATE TABLE IF NOT EXISTS Guarantees (
        ID VARCHAR(32) PRIMARY KEY,                 -- 担保ID，格式如GUA+日期+随机数
        CreatorOpenID VARCHAR(50) NOT NULL,         -- 创建者OpenID
        ParticipantOpenID VARCHAR(50),              -- 参与者OpenID
        Deposit DECIMAL(10, 2) NOT NULL,            -- 押金金额
        Amount DECIMAL(10, 2) NOT NULL,             -- 订单金额
        CreatorRole VARCHAR(10) NOT NULL,           -- 创建者角色：worker(打手) 或 boss(老板)
        Status VARCHAR(20) NOT NULL,                -- 状态：created(已创建), waiting_join(等待加入), processing(进行中), completed(已完成), cancelled(已取消)
        Remark TEXT,                                -- 备注信息
        CreateTime DATETIME NOT NULL,               -- 创建时间
        CreatorPayTime DATETIME,                    -- 创建者支付时间
        ParticipantPayTime DATETIME,                -- 参与者支付时间
        CompleteTime DATETIME,                      -- 完成时间
        CancelTime DATETIME                         -- 取消时间
    );`
    _, err = db.Exec(createGuaranteesTableSQL)
    if err != nil {
        return fmt.Errorf("error creating Guarantees table: %w", err)
    }
    
    // 支付记录表（使用CREATE TABLE IF NOT EXISTS，所以即使之前已创建，也不会报错）
    // 注意：这里存在重复创建的问题，但使用IF NOT EXISTS可以防止错误
    anotherGuaranteePaymentsTableSQL := `CREATE TABLE IF NOT EXISTS GuaranteePayments (
        ID INTEGER PRIMARY KEY AUTOINCREMENT,       -- 支付记录ID
        GuaranteeID VARCHAR(32) NOT NULL,           -- 关联的担保ID
        OpenID VARCHAR(50) NOT NULL,                -- 支付者OpenID
        Amount DECIMAL(10, 2) NOT NULL,             -- 支付金额
        TradeType VARCHAR(50) NOT NULL,             -- 交易类型
        OutTradeNo VARCHAR(64) NOT NULL,            -- 商户订单号
        PrepayID VARCHAR(64) NOT NULL,              -- 预支付交易会话标识
        TransactionID VARCHAR(64),                  -- 微信支付订单号
        Status VARCHAR(20) DEFAULT 'pending',       -- 状态：pending(待支付), success(成功), refunded(已退款)
        CreateTime DATETIME NOT NULL,               -- 创建时间
        PayTime DATETIME,                           -- 支付时间
        RefundTime DATETIME,                        -- 退款时间
        ServiceFee DECIMAL(10,2) DEFAULT 0.00       -- 服务费
    );`
    _, err = db.Exec(anotherGuaranteePaymentsTableSQL)
    if err != nil {
        return fmt.Errorf("error updating GuaranteePayments table: %w", err)
    }
    
    // 创建索引
    createIndicesSQL := []string{
        `CREATE INDEX IF NOT EXISTS idx_guarantees_creator ON Guarantees(CreatorOpenID);`,
        `CREATE INDEX IF NOT EXISTS idx_guarantees_participant ON Guarantees(ParticipantOpenID);`,
        `CREATE INDEX IF NOT EXISTS idx_guarantees_status ON Guarantees(Status);`,
        `CREATE INDEX IF NOT EXISTS idx_guarantees_create_time ON Guarantees(CreateTime);`,
        `CREATE INDEX IF NOT EXISTS idx_payments_guarantee_id ON GuaranteePayments(GuaranteeID);`,
        `CREATE INDEX IF NOT EXISTS idx_payments_openid ON GuaranteePayments(OpenID);`,
        `CREATE INDEX IF NOT EXISTS idx_payments_out_trade_no ON GuaranteePayments(OutTradeNo);`,
        `CREATE INDEX IF NOT EXISTS idx_payments_status ON GuaranteePayments(Status);`,
    }
    
    for _, indexSQL := range createIndicesSQL {
        _, err = db.Exec(indexSQL)
        if err != nil {
            return fmt.Errorf("error creating index: %w", err)
        }
    }
	
    createBridgeMessagesTablleSQL := `CREATE TABLE IF NOT EXISTS BridgeMessages (
        BridgeID TEXT NOT NULL,
        Message TEXT NOT NULL,
        Role  TEXT ,
        Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
    );`
    _, err = db.Exec(createBridgeMessagesTablleSQL)
    if err != nil {
        return fmt.Errorf("error creating BridgeMessages table: %w", err)
    }
	
    // 创建好友表
    _, err = db.Exec(`
        CREATE TABLE IF NOT EXISTS friends (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            userName TEXT UNIQUE NOT NULL,
            nickName TEXT,
            remark TEXT,
            bigHeadImgUrl TEXT
        )
    `)
    if err != nil {
        return err
    }

    // 创建群组表
    _, err = db.Exec(`
        CREATE TABLE IF NOT EXISTS groups (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            userName TEXT UNIQUE NOT NULL,
            nickName TEXT
        )
    `)
    if err != nil {
        return err
    }
    
    createRankPricesTableSQL := `CREATE TABLE IF NOT EXISTS RankPrices (
        Rank TEXT PRIMARY KEY,
        Price INTEGER NOT NULL,
        StarCost INTEGER NOT NULL,
        RankOrder INTEGER NOT NULL
    );`
    _, err = db.Exec(createRankPricesTableSQL)
    if err != nil {
        fmt.Printf("Error creating RankPrices table: %v\n", err)
        return err
    }
	
    // Create member_stars table
    createMemberStarsTableSQL := `CREATE TABLE IF NOT EXISTS member_stars (
        GroupID TEXT NOT NULL,
        UserName TEXT NOT NULL,
        StarsCount INTEGER,
        PRIMARY KEY (GroupID, UserName)
    );`
    _, err = db.Exec(createMemberStarsTableSQL)
    if err != nil {
        fmt.Printf("Error creating member stars table: %v\n", err)
        return err
    }

    return nil
}

func main() {
	if err := initializeDatabase(); err != nil {
        fmt.Println("Failed to initialize the database")
        return
    }
    defer db.Close()
    defer db2.Close()
	// 调用更新通讯录的函数
	if err := updateContacts(); err != nil {
		fmt.Println("Error updating contacts:", err)
	}
    initGroupMonitor(db)
    scheduleBridgeForwardingTask(db)
    scheduleDailyTask(db) // 启动定时任务
    // 启动定时任务
    scheduleInactivityReminder(db)
	// 并发运行两个路由函数
	go luyou1()
	go luyou2()

	// 防止主协程退出
	select {}
}
func isNumericContent(content string) bool {
    content = strings.Replace(content, "[", "", -1)
    content = strings.Replace(content, "]", "", -1)
    // 使用正则表达式检查字符串是否以数字结尾
    match, _ := regexp.MatchString(`\d$`, content)
    return match
}
func sanitizeFileName(fileName string) string {
    // List of characters that are not allowed in Windows file names
    invalidChars := []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|"}

    // Replace each invalid character with an underscore or remove them
    for _, invalidChar := range invalidChars {
        fileName = strings.ReplaceAll(fileName, invalidChar, "_")
    }

    return fileName
}
func scheduleInactivityReminder(db *sql.DB) {
    go func() {
        for {
            time.Sleep(2 * time.Hour) // 设置检查间隔

            query := `SELECT ID, WeChatUser, OrderType FROM Bridges WHERE IsActive = 1 AND (GameID = "" OR GameID IS NULL)`
            rows, err := db.Query(query)
            if err != nil {
                fmt.Printf("查询活跃桥失败: %v\n", err)
                continue
            }

            for rows.Next() {
                var bridgeID, weChatUser, orderType string
                err = rows.Scan(&bridgeID, &weChatUser, &orderType)
                if err != nil {
                    fmt.Printf("读取活跃桥信息失败: %v\n", err)
                    continue
                }

                userName, err := findUserNameByNickName(weChatUser)
                if err != nil {
                    fmt.Printf("查找用户失败: %v\n", err)
                    continue
                }

                switch orderType {
                case "车队":
                    message1 := "哥，你打完了的话复制替换下面的话（去不去掉括号都行）记录一下，谢谢配合"
                    message2 := "[老板发的名字][净胜]+[金额]"
                    sendTextMessage(message1, userName)
                    sendTextMessage(message2, userName)

                case "代练":
                    message1 := fmt.Sprintf("哥，发一下进度，记录一下，复制下面的话，填上当前进度，格式如：#%s:星耀22星", bridgeID)
                    message2 := fmt.Sprintf("#%s:（进度）", bridgeID)
                    sendTextMessage(message1, userName)
                    sendTextMessage(message2, userName)

                default:
                    // 其他订单类型不发送消息
                }
            }
            rows.Close()
        }
    }()
}
func scheduleBridgeForwardingTask(db *sql.DB) {
    go func() {
        ticker := time.NewTicker(60 * time.Second)
        for {
            select {
            case <-ticker.C:
                if isBridgeForwardingEnabled {
                    // 检查Bridge结构中的WeChatUser字段是否为空
                    // 并根据订单模式发送消息
                    checkAndForwardBridgeMessages(db)
                }
            }
        }
    }()
}
func checkAndForwardBridgeMessages(db *sql.DB) {
    rows, err := db.Query("SELECT ID, GroupID, GroupName, Msg, OrderType FROM Bridges WHERE WeChatUser = '' AND IsActive = 1")
    if err != nil {
        fmt.Printf("Error querying bridges: %v\n", err)
        return
    }
    defer rows.Close()

    for rows.Next() {
        var bridge Bridge
        err := rows.Scan(&bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.Msg, &bridge.OrderType)
        if err != nil {
            fmt.Printf("Error scanning bridge: %v\n", err)
            continue
        }

        // 确定订单类型
        orderType := bridge.OrderType

        // 判断是内部接单模式还是外部接单模式
        if isInternalOrderMode {
            switch orderType {
            case "车队":
                forwardMessageToAllGroupsneibu(db, bridge.Msg)
            case "陪玩":
                forwardMessageToAllGroupsneibu(db, bridge.Msg)
            case "小姐姐":
                forwardMessageToAllGroupsneibu(db, bridge.Msg)
            case "代练":
                forwardMessageToAllGroupsneibu(db, bridge.Msg)
            }
        } else {
            // 外部接单模式的消息转发逻辑
            switch orderType {
            case "车队":
                forwardMessageToAllGroupswaibu(db, bridge.Msg)
            case "陪玩":
                forwardMessageToAllGroupspeiwan(db, bridge.Msg)
            case "小姐姐":
                forwardMessageToAllGroupsxjj(db, bridge.Msg)
            case "代练":
                forwardMessageToAllGroupsdailian(db, bridge.Msg)
            }
        }
    }
}
func scheduleDailyTask(db *sql.DB) {
    go func() {
        for {
            // 获取当前时间
            now := time.Now()

            // 计算下一个中午和次日6点的时间
            nextDay := now.Add(24 * time.Hour)
            nextMidnight := time.Date(nextDay.Year(), nextDay.Month(), nextDay.Day(), 0, 0, 0, 0, nextDay.Location())
            nextSixAM := time.Date(nextDay.Year(), nextDay.Month(), nextDay.Day(), 7, 0, 0, 0, nextDay.Location())

            // 等待直到下一个中午
            time.Sleep(time.Until(nextMidnight))

            // 等待直到早上6点
            time.Sleep(time.Until(nextSixAM))

            // 执行发送统计消息的任务
            sendStarSummaryToGroups()

            // 每周日执行的任务
            if now.Weekday() == time.Sunday {
                sendWeeklySummaryToGroups() // 发送周统计消息
            }
        }
    }()
}

func sendWeeklySummaryToGroups() {
    var err error

    // 获取数据库中记录的群名及对应的星数统计
    rows, err := db.Query(`
        SELECT GroupName, GroupUserNickName, SUM(Stars) as TotalStars
        FROM Bridges
        WHERE CreatedAt >= datetime('now', '-7 days')
        GROUP BY GroupName, GroupUserNickName
    `)
    if err != nil {
        fmt.Printf("Error querying weekly summary: %v\n", err)
        return
    }
    defer rows.Close()

    groupStars := make(map[string]map[string]int)
    groupTotalStars := make(map[string]int)
    for rows.Next() {
        var groupName, userNickName string
        var totalStars int
        err = rows.Scan(&groupName, &userNickName, &totalStars)
        if err != nil {
            fmt.Printf("Error reading row: %v\n", err)
            continue
        }

        if _, exists := groupStars[groupName]; !exists {
            groupStars[groupName] = make(map[string]int)
        }
        groupStars[groupName][userNickName] = totalStars
        groupTotalStars[groupName] += totalStars
    }

    // 获取数据库中的群组信息
    rows, err = db.Query("SELECT userName, nickName FROM groups")
    if err != nil {
        fmt.Printf("Error fetching groups from database: %v\n", err)
        return
    }
    defer rows.Close()

    groupNameToUserName := make(map[string]string) // 用于映射群组名称到群组用户名
    for rows.Next() {
        var userName, nickName string
        err := rows.Scan(&userName, &nickName)
        if err != nil {
            fmt.Printf("Error reading group data: %v\n", err)
            continue
        }
        groupNameToUserName[nickName] = userName
    }

    if err := rows.Err(); err != nil {
        fmt.Printf("Error iterating over rows: %v\n", err)
        return
    }

    // 遍历群组和统计数据，并发送消息
    for groupName, users := range groupStars {
        groupUserName, ok := groupNameToUserName[groupName]
        if !ok {
            fmt.Printf("Group not found for name: %s\n", groupName)
            continue
        }

        var topUser string
        var topStars int
        for user, stars := range users {
            if stars > topStars {
                topStars = stars
                topUser = user
            }
        }

        // 构建并发送消息
        message := fmt.Sprintf("🌟 本周星辰之旅 🌟\n\n🏆 最耀眼的星: %s\n🌟 星数累积: %d 星\n\n🌟 群总上星数: %d 星\n\n🌈 新的一周，新的挑战！\n让我们继续一起冲刺，摘下更多的星辰！加油！", topUser, topStars, groupTotalStars[groupName])

        // 使用 sendTextMessage 发送消息到群组
        sendTextMessage(message, groupUserName)
    }
}
func sendStarSummaryToGroups() {
    var err error

    // 定义一个结构体来表示群组信息
    type Group struct {
        ID       string
        UserName string
        NickName string
    }

    // 定义一个结构体来表示每个用户的星数
    type UserStars struct {
        NickName  string
        TotalStars int
    }

    // 获取数据库中记录的群名及对应的星数统计
    rows, err := db.Query(`
        SELECT GroupName, GroupUserNickName, SUM(Stars) as TotalStars
        FROM Bridges
        WHERE CreatedAt >= datetime('now', '-1 days')
        GROUP BY GroupName, GroupUserNickName
    `)
    if err != nil {
        fmt.Printf("Error querying star summary: %v\n", err)
        return
    }
    defer rows.Close()

    // 定义一个映射，存储每个群组的用户和星数
    groupStars := make(map[string]map[string]int)
    for rows.Next() {
        var groupName, userNickName string
        var totalStars int
        err = rows.Scan(&groupName, &userNickName, &totalStars)
        if err != nil {
            fmt.Printf("Error reading row: %v\n", err)
            continue
        }

        if _, exists := groupStars[groupName]; !exists {
            groupStars[groupName] = make(map[string]int)
        }
        groupStars[groupName][userNickName] = totalStars
    }

    // 获取数据库中的群组信息
    rows, err = db.Query("SELECT userName, nickName FROM groups")
    if err != nil {
        fmt.Printf("Error fetching groups from database: %v\n", err)
        return
    }
    defer rows.Close()

    var groups []Group
    groupNameToUserName := make(map[string]string) // 用于映射群组名称到群组用户名
    for rows.Next() {
        var group Group
        err := rows.Scan(&group.UserName, &group.NickName)
        if err != nil {
            fmt.Printf("Error reading group data: %v\n", err)
            continue
        }
        groups = append(groups, group)
        groupNameToUserName[group.NickName] = group.UserName
    }

    if err := rows.Err(); err != nil {
        fmt.Printf("Error iterating over rows: %v\n", err)
        return
    }

    // 遍历群组和统计数据，并发送消息
    for groupName, users := range groupStars {
        groupUserName, ok := groupNameToUserName[groupName]
        if !ok {
            fmt.Printf("Group not found for name: %s\n", groupName)
            continue
        }

        var topUser string
        var topStars int
        for user, stars := range users {
            if stars > topStars {
                topStars = stars
                topUser = user
            }
        }

        // 构建并发送第一条消息
        message1 := fmt.Sprintf(` ⭐.°。✨ *´¨
        .· ´¸.·*´¨✨ ¸.·*¨✨
        ✨　¸✨·´ ✨¸.·’* ✨

        -🎀  🎀-

        把星空挂在指尖ᵇᵘˡⁱⁿᵍ✨

        就算阴天也不怕看不到星星💫

        ╭═════════☀═╮
        恭喜 %s 上星最多
        昨日上分：%d星
        寄语：向阳而生 平安健康
        ╰══ 超级感谢biubiu  ══╯  
        ✨  🧚🏻‍♀️     ✨
        🍃 ♡⃝♡⃝♡⃝♡⃝♡ ♡⃝♡⃝♡⃝♡⃝♡ 🍃

        ✨ 陪伴胜过言语 🌠

        💌 细节胜过情话 💐

        ⊹ ✨            ·   ☆            ✨* 
        ✩•‿• ʜᴀᴠᴇ ᴀ ɢᴏᴏᴅ ᴛɪᴍᴇ♡ ♡ ♡`, topUser, topStars)
        sendTextMessage(message1, groupUserName)

        // 生成排行榜消息
        var usersSorted []string
        for user := range users {
            usersSorted = append(usersSorted, user)
        }
        sort.Slice(usersSorted, func(i, j int) bool {
            return users[usersSorted[i]] > users[usersSorted[j]]
        })

        // 获取广告信息
        var guanggao string
        err = db.QueryRow("SELECT event_text FROM current_event WHERE id = 9 AND event_title = '工作室的广告'").Scan(&guanggao)
        if err != nil {
            fmt.Println("查询广告失败:", err)
            return
        }

        // 构建排行榜消息
        var messageBuilder strings.Builder
        messageBuilder.WriteString("🚉🚉🚉")
        messageBuilder.WriteString(guanggao) // 使用数据库中的广告替代固定文本
        messageBuilder.WriteString("🚉🚉🚉\n====上分排行榜====\n")

        for i, user := range usersSorted {
            messageBuilder.WriteString(fmt.Sprintf("%d. %s 上了 %d 星\n", i+1, user, users[user]))
        }
        messageBuilder.WriteString("☀☀☀ 祝各位帅哥美女们，在新的一天，玩的开心，玩的愉快！☀☀☀")
        sendTextMessage(messageBuilder.String(), groupUserName)
    }
}
func extractTransferID(strContent string) (string, error) {
	// 使用正则表达式提取 transferid
	re := regexp.MustCompile(`<transferid><!\[CDATA\[(.*?)\]\]></transferid>`)
	matches := re.FindStringSubmatch(strContent)
	if len(matches) < 2 {
		return "", fmt.Errorf("未能提取到 transferid")
	}
	return matches[1], nil
}

func extractAmount(strContent string) (float64, error) {
	// 使用正则表达式提取金额（feedesc 标签中的内容）
	re := regexp.MustCompile(`<feedesc><!\[CDATA\[(.*?)\]\]></feedesc>`)
	matches := re.FindStringSubmatch(strContent)
	if len(matches) < 2 {
		return 0, fmt.Errorf("未能提取到金额")
	}

	// 提取金额部分并转换为浮动数字
	amountStr := matches[1]
	amountStr = strings.TrimPrefix(amountStr, "￥") // 去掉人民币符号
	amount, err := strconv.ParseFloat(amountStr, 64)
	if err != nil {
		return 0, fmt.Errorf("金额转换失败: %w", err)
	}
	return amount, nil
}
// 生成一个随机的充值码
func generateRechargeCode() string {
    rand.Seed(time.Now().UnixNano())
    letters := "0123456789"
    result := make([]byte, 19)
    for i := range result {
        result[i] = letters[rand.Intn(len(letters))]
    }
    return string(result)
}
// 将转账金额、充值码和用户名记录到数据库中
func insertRechargeRecord(db *sql.DB, amount float64, rechargeCode, userName string) error {
    // 向数据库的充值记录表插入一条记录，包括用户名
    _, err := db.Exec("INSERT INTO recharge_records (amount, recharge_code, user_name, used) VALUES (?, ?, ?, 0)", amount, rechargeCode, userName)
    return err
}
func extractPaySubType(strContent string) (int, error) {
    re := regexp.MustCompile(`<paysubtype>(\d+)</paysubtype>`)
    matches := re.FindStringSubmatch(strContent)
    if len(matches) < 2 {
        return 0, fmt.Errorf("未能提取到 paysubtype")
    }

    // 将提取到的字符串转换为整数
    paysubtype, err := strconv.Atoi(matches[1])
    if err != nil {
        return 0, fmt.Errorf("paysubtype 转换失败: %w", err)
    }
    return paysubtype, nil
}
// luyou1 路由函数
func luyou1() {
	r := gin.Default()
    r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})
    r.Static("/static", "./static")
	r.POST("/callback", func(c *gin.Context) {
		var callback CallbackData
	
		// 绑定 JSON 数据到结构体
		if err := c.ShouldBindJSON(&callback); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"status":  "error",
				"message": err.Error(),
			})
			return
		}
        if callback.Msg == "XML消息" {
            fmt.Println("收到XML消息，开始处理...")
            
            // 检查是否包含王者段位和陪玩价格信息
            if strings.Contains(callback.Data.Content, "王者1-10") && 
               strings.Contains(callback.Data.Content, "王者10-20") && 
               strings.Contains(callback.Data.Content, "陪玩价格") {
                
                fmt.Println("检测到王者荣耀价格表公告，准备保存...")
                
                // 提取公告内容
                textAnnouncementRegex := regexp.MustCompile(`<textannouncement><!\[CDATA\[([\s\S]*?)\]\]></textannouncement>`)
                matches := textAnnouncementRegex.FindStringSubmatch(callback.Data.Content)
                
                if len(matches) >= 2 {
                    content := matches[1]
                    fmt.Println("从 textannouncement 标签提取到内容")
                    
                    // 插入或更新逻辑
                    id := 13
                    title := "发单价格表"
                    
                    // 查询是否已存在
                    var exists bool
                    checkQuery := "SELECT EXISTS(SELECT 1 FROM current_event WHERE id = ?);"
                    err := db.QueryRow(checkQuery, id).Scan(&exists)
                    if err != nil {
                        fmt.Printf("查询数据库失败: %s\n", err)
                        return
                    }
                    
                    if exists {
                        // 更新
                        updateQuery := "UPDATE current_event SET event_title = ?, event_text = ? WHERE id = ?;"
                        _, err = db.Exec(updateQuery, title, content, id)
                        if err != nil {
                            fmt.Printf("更新数据库失败: %s\n", err)
                            return
                        }
                        fmt.Println("价格表更新成功")
                    } else {
                        // 插入
                        insertQuery := "INSERT INTO current_event (id, event_title, event_text) VALUES (?, ?, ?);"
                        _, err = db.Exec(insertQuery, id, title, content)
                        if err != nil {
                            fmt.Printf("插入数据库失败: %s\n", err)
                            return
                        }
                        fmt.Println("价格表插入成功")
                    }
                
                    return
                } else {
                    fmt.Println("未能提取到公告内容，跳过保存")
                }
            } else {
                fmt.Println("群公告不包含目标价格信息，跳过处理")
            }
        }
		// 判断 Msg 是否为 "实时消息"
		if callback.Msg == "实时消息" {
            if callback.Data.TypeInfo == "XML消息(转账)" {
                // 提取 paysubtype
                paysubtype, err := extractPaySubType(callback.Data.StrContent)
                if err != nil {
                    log.Printf("提取 paysubtype 失败: %s\n", err)
                    return
                }
            
                // 只有在收账（paysubtype == 1）时才执行相关逻辑
                if paysubtype == 1 {
                    // 提取 transferID
                    transferID, err := extractTransferID(callback.Data.StrContent)
                    if err != nil {
                        log.Printf("提取 transferid 失败: %s\n", err)
                        return
                    }
            
                    // 发送 POST 请求进行处理
                    err = sendPostRequest(transferID, callback.Data.UserName, callback.Port)
                    if err != nil {
                        log.Printf("发送请求失败: %s\n", err)
                        return
                    }
            
                    // 提取金额
                    amount, err := extractAmount(callback.Data.StrContent)
                    if err != nil {
                        log.Printf("提取金额失败: %s\n", err)
                        return
                    }
            
                    fmt.Printf("收到转账，金额：%.2f\n", amount)
            
                    // 只有在金额不为0时，才继续执行相关逻辑
                    if amount != 0 {
                        // 生成唯一的充值码
                        rechargeCode := generateRechargeCode()
            
                        // 将转账金额、充值码和用户信息记录到数据库中
                        err := insertRechargeRecord(db, amount, rechargeCode, callback.Data.UserName)
                        if err != nil {
                            log.Printf("插入充值记录失败: %s\n", err)
                            return
                        }
            
                        // 向用户发送兑换码和相关信息
                        sendTextMessagePort(fmt.Sprintf("兑换码：%s", rechargeCode), callback.Data.UserName, callback.Port)
                        sendTextMessagePort("请复制上面这句话发送到微信群中获取星卷。", callback.Data.UserName, callback.Port)
                    }
                } else {
                    fmt.Println("确认收账消息，跳过处理")
                }
                return
            }
            if callback.Port == 12590 {
                handleMessages(callback.Data)
            } else{
                AIMessages(callback.Data, callback.Port)
            }
		} else if callback.Msg == "好友请求" {
			fmt.Println("处理好友添加消息")
			if callback.Data.Chatroomusername == "18466265933@chatroom" {
				fmt.Println("来自 chatroomusername 为 18466265933@chatroom 的好友请求，跳过处理")
				return
			}
			// 提取好友添加消息中的 encryptUserName 和 ticket
			encryptUserName := callback.Data.EncryptUserName
			ticket := callback.Data.Ticket
	
			// 检查是否成功提取到值
			if encryptUserName == "" || ticket == "" {
				fmt.Println("好友添加消息中缺少 encryptUserName 或 ticket")
				return
			}
	
			// 调用 POST 请求处理好友添加
			err := sendAddFriendRequest(encryptUserName, ticket, callback.Port)
			if err != nil {
				fmt.Printf("发送好友添加请求失败: %s\n", err)
				return
			}
	
			fmt.Println("好友添加请求发送成功")
		}  else {
			// 非 "实时消息"，直接返回成功响应
			fmt.Println("非实时消息，跳过处理")
			c.JSON(http.StatusOK, gin.H{
				"status":  "success",
				"message": "Non-realtime message ignored",
			})
			return
		}
	
		// 返回响应
		c.JSON(http.StatusOK, gin.H{
			"status":  "success",
			"message": "Data received on luyou1",
		})
	})
    r.LoadHTMLGlob("templates/*.html")
    r.Static("/js", "./js")
    r.Static("/css", "./css")
    r.Static("/image", "./image") // 与 /images 不冲突
    r.Static("/images", "./images")
    r.Static("/voice", "./voice")
    r.Static("/jiaoyi", "./jiaoyi")
    r.Static("/shuoming", "./shuoming")
    // 会话管理中间件配置
    store := cookie.NewStore([]byte("very-secret"))
    r.Use(sessions.Sessions("mysession", store))
    r.GET("/get_moban", func(c *gin.Context) {
        log.Println("开始处理 /get_moban 请求")
    
        // 查询数据库获取模板信息，包括使用次数
        query := `SELECT TemplateName, OrderDetails, RestrictedOrderDetails, IsCommonTemplate, UsageCount FROM Templates`
        log.Printf("执行的SQL查询: %s", query)
    
        rows, err := db.Query(query)
        if err != nil {
            log.Printf("查询数据库时出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取模板信息"})
            return
        }
        defer rows.Close()
    
        var templates []gin.H
    
        for rows.Next() {
            var templateName, orderDetails, restrictedOrderDetails string
            var isCommonTemplate bool
            var usageCount int // 使用次数
    
            err = rows.Scan(&templateName, &orderDetails, &restrictedOrderDetails, &isCommonTemplate, &usageCount)
            if err != nil {
                log.Printf("扫描数据库结果时出错: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "解析模板信息失败"})
                return
            }
    
            // 打印从数据库中获取的每条模板数据
            log.Printf("获取到的模板信息: TemplateName=%s, OrderDetails=%s, RestrictedOrderDetails=%s, IsCommonTemplate=%v, UsageCount=%d",
                templateName, orderDetails, restrictedOrderDetails, isCommonTemplate, usageCount)
    
            // 如果某些字段为空，返回默认值
            if orderDetails == "" {
                orderDetails = "无"
            }
            if restrictedOrderDetails == "" {
                restrictedOrderDetails = "无"
            }
    
            templates = append(templates, gin.H{
                "template_name":           templateName,
                "order_details":           orderDetails,
                "restricted_order_details": restrictedOrderDetails,
                "is_common_template":      isCommonTemplate,
                "usage_count":             usageCount, // 返回使用次数
            })
        }
    
        if len(templates) == 0 {
            log.Println("未找到任何模板数据")
        } else {
            log.Printf("成功获取 %d 条模板数据", len(templates))
        }
    
        c.JSON(http.StatusOK, templates)
        log.Println("模板数据成功返回给客户端")
    })  
    r.POST("/api/conversations/list", func(c *gin.Context) {
        // 请求参数结构体
        type ConversationListRequest struct {
            Code string `json:"code"` // 微信授权码
        }
    
        var req ConversationListRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "请求参数错误",
            })
            return
        }
    
        // 获取 OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
    
        // 1. 根据 OpenID 查询用户信息
        var username string
        err = db.QueryRow("SELECT wechatname FROM users WHERE openid = ?", openid).Scan(&username)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    3,
                "message": "查询用户信息失败",
            })
            return
        }
    
        // 2. 根据 username 查询 friends 表获取 nickName
        var nickname string
        err = db.QueryRow("SELECT nickName FROM friends WHERE userName = ?", username).Scan(&nickname)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    4,
                "message": "查询好友信息失败",
            })
            return
        }
    
        // 3. 根据 nickname 查询 Bridges 表中符合条件的订单
        sqlQuery := `
            SELECT ID, Msg, OrderType, CreatedAt
            FROM Bridges
            WHERE WeChatUser = ? AND IsActive = 1
            ORDER BY CreatedAt DESC
        `
        
        rows, err := db.Query(sqlQuery, nickname)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    5,
                "message": "查询订单列表失败",
            })
            return
        }
        defer rows.Close()
    
        // 处理查询结果
        var conversations []gin.H
        
        for rows.Next() {
            var id, msg, orderType, createdAtStr string
            
            // 查询结果赋值
            err := rows.Scan(&id, &msg, &orderType, &createdAtStr)
            if err != nil {
                continue
            }
            
            // 直接使用原始字符串格式，不尝试解析
            item := gin.H{
                "ID":        id,
                "Msg":       msg,
                "OrderType": orderType,
                "CreatedAt": createdAtStr, // 直接使用数据库中的原始时间字符串
                "IsActive":  true,         // 由于查询条件已限定 IsActive = 1
            }
            
            conversations = append(conversations, item)
        }
    
        // 返回结果
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "获取成功",
            "data":    conversations,
        })
    })
    // 获取用户收费明细
    r.GET("/api/user/fee-details", func(c *gin.Context) {
        code := c.Query("code")
        if code == "" {
            c.JSON(http.StatusBadRequest, gin.H{
                "code": 1,
                "message": "缺少必要参数",
            })
            return
        }

        // 获取OpenID
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code": 2,
                "message": "获取用户信息失败",
            })
            return
        }

        // 查询用户的收费明细
        rows, err := db.Query(`
            SELECT ID, FeeType, Amount, CreateTime 
            FROM UserFees 
            WHERE OpenID = ? 
            ORDER BY CreateTime DESC 
            LIMIT 50`, openid)
        
        if err != nil {
            log.Printf("[ERROR] 查询收费明细失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code": 3,
                "message": "查询收费明细失败",
            })
            return
        }
        defer rows.Close()

        var feeDetails []map[string]interface{}
        for rows.Next() {
            var id string
            var feeType string
            var amount float64
            var createTime string

            if err := rows.Scan(&id, &feeType, &amount, &createTime); err != nil {
                log.Printf("[ERROR] 读取收费明细记录失败: %v", err)
                continue
            }

            feeDetails = append(feeDetails, map[string]interface{}{
                "id": id,
                "feeType": feeType,
                "amount": amount,
                "createTime": createTime,
            })
        }

        c.JSON(http.StatusOK, gin.H{
            "code": 0,
            "message": "success",
            "data": feeDetails,
        })
    })

    // 获取用户交易记录
    r.GET("/api/user/transactions", func(c *gin.Context) {
        code := c.Query("code")
        if code == "" {
            c.JSON(http.StatusBadRequest, gin.H{
                "code": 1,
                "message": "缺少必要参数",
            })
            return
        }

        // 获取OpenID
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code": 2,
                "message": "获取用户信息失败",
            })
            return
        }

        // 查询用户的交易记录
        rows, err := db.Query(`
            SELECT ID, TransactionType, Amount, Status, CreateTime 
            FROM UserTransactions 
            WHERE OpenID = ? 
            ORDER BY CreateTime DESC 
            LIMIT 50`, openid)
        
        if err != nil {
            log.Printf("[ERROR] 查询交易记录失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code": 3,
                "message": "查询交易记录失败",
            })
            return
        }
        defer rows.Close()

        var transactions []map[string]interface{}
        for rows.Next() {
            var id string
            var transactionType string
            var amount float64
            var status string
            var createTime string

            if err := rows.Scan(&id, &transactionType, &amount, &status, &createTime); err != nil {
                log.Printf("[ERROR] 读取交易记录失败: %v", err)
                continue
            }

            transactions = append(transactions, map[string]interface{}{
                "id": id,
                "transactionType": transactionType,
                "amount": amount,
                "status": status,
                "createTime": createTime,
            })
        }

        c.JSON(http.StatusOK, gin.H{
            "code": 0,
            "message": "success",
            "data": transactions,
        })
    })
    // 退款回调处理
    r.POST("/api/guarantee/refundNotify", func(c *gin.Context) {
        ctx := context.Background()
        rawBody, _ := io.ReadAll(c.Request.Body)
        log.Printf("[INFO] 收到退款回调请求: %s", string(rawBody))
        
        c.Request.Body = io.NopCloser(bytes.NewBuffer(rawBody))
        
        apiV3Key := "MIIEKDCCAxCgAwIBAgIUUqirwt6exDMy" // 替换为你的实际密钥
        platformCertPath := "./wechatpay_cert_5714802C1232EFD19CED7478282FC8E1A088DD84.pem"
        
        platformCert, err := utils.LoadCertificateWithPath(platformCertPath)
        if err != nil {
            log.Printf("[ERROR] 加载微信支付平台证书失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        certVisitor := core.NewCertificateMapWithList([]*x509.Certificate{platformCert})
        handler := notify.NewNotifyHandler(apiV3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))
        
        refundNotify := make(map[string]interface{})
        _, err = handler.ParseNotifyRequest(ctx, c.Request, &refundNotify)
        if err != nil {
            log.Printf("[ERROR] 解析退款通知失败: %v", err)
            c.String(http.StatusBadRequest, "FAIL")
            return
        }
        
        log.Printf("[INFO] 退款回调解析成功，内容: %+v", refundNotify)
        
        // 获取退款单号
        outRefundNo, ok := refundNotify["out_refund_no"].(string)
        if !ok {
            log.Printf("[ERROR] 退款通知中缺少 out_refund_no 字段")
            c.Status(http.StatusBadRequest)
            return
        }
        
        // 获取退款状态
        status, ok := refundNotify["refund_status"].(string)
        if !ok {
            log.Printf("[ERROR] 退款通知中缺少 refund_status 字段")
            c.Status(http.StatusBadRequest)
            return
        }
        
        // 更新退款记录状态
        _, err = db.Exec(
            `UPDATE Refunds SET 
            Status = ?, 
            UpdateTime = ? 
            WHERE OutRefundNo = ?`,
            status,
            time.Now().Format("2006-01-02 15:04:05"),
            outRefundNo,
        )
        if err != nil {
            log.Printf("[WARNING] 更新退款记录状态失败: %v", err)
        }
        
        // 回复微信支付平台
        c.String(http.StatusOK, "SUCCESS")
        log.Printf("[INFO] 退款通知处理成功，退款单号: %s，状态: %s", outRefundNo, status)
    })
    r.POST("/api/guarantee/preparePayment", func(c *gin.Context) {
        // 请求参数结构体
        type PreparePaymentRequest struct {
            Deposit    float64 `json:"deposit"`   // 押金
            Amount     float64 `json:"amount"`    // 订单金额
            Role       string  `json:"role"`      // 角色: worker(打手) 或 boss(老板)
            Remark     string  `json:"remark"`    // 备注信息
            Code       string  `json:"code"`      // 微信授权码
            IsCreating bool    `json:"isCreating"`// 是否为创建担保
        }
    
        var req PreparePaymentRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("[ERROR] 解析准备支付请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "请求参数错误",
            })
            return
        }
    
        log.Printf("[INFO] 收到准备支付请求: %+v", req)
    
        // 获取 OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)
    
        // 生成临时订单ID
        tempOrderId := fmt.Sprintf("TEMP%s%d", time.Now().Format("20060102"), time.Now().UnixNano()%1000000)
        
        // 根据角色确定支付金额
        payAmount := req.Deposit
        if req.Role == "boss" {
            payAmount = req.Amount
        }
        
        // 计算服务费 (1%)，最低为1元
        serviceFee := payAmount * 0.01
        if serviceFee < 1.0 {
            serviceFee = 1.0
        }
        
        // 计算总支付金额 (原金额 + 服务费)
        totalPayAmount := payAmount + serviceFee
        
        // 创建负数服务费用于存储到数据库
        negativeServiceFee := -math.Abs(serviceFee)
        
        log.Printf("[INFO] 计算服务费: 原金额 %.2f, 服务费 %.2f, 总额 %.2f, 负数服务费 %.2f", 
                   payAmount, serviceFee, totalPayAmount, negativeServiceFee)
        
        // 存储临时订单数据，包含服务费信息（使用负数）
        _, err = db.Exec(
            `INSERT INTO TempGuarantees 
            (ID, OpenID, Deposit, Amount, Role, Remark, ServiceFee, OriginalAmount, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            tempOrderId,
            openid,
            req.Deposit,
            req.Amount,
            req.Role,
            req.Remark,
            negativeServiceFee,  // 存储负数服务费
            payAmount,           // 存储原始支付金额（不含服务费）
            time.Now().Format("2006-01-02 15:04:05"),
        )
        if err != nil {
            log.Printf("[ERROR] 存储临时担保信息失败: %v", err)
            // 尝试使用旧的表结构
            _, err = db.Exec(
                `INSERT INTO TempGuarantees 
                (ID, OpenID, Deposit, Amount, Role, Remark, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?)`,
                tempOrderId,
                openid,
                req.Deposit,
                req.Amount,
                req.Role,
                req.Remark,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            if err != nil {
                log.Printf("[ERROR] 使用旧表结构存储临时担保信息也失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{
                    "code":    3,
                    "message": "准备支付失败",
                })
                return
            }
        }
    
        // 初始化微信支付客户端
        client, err := InitWeChatPayClient()
        if err != nil {
            log.Printf("[ERROR] 初始化微信支付客户端失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    4,
                "message": "支付请求失败",
            })
            return
        }
    
        // 生成支付请求，使用包含服务费的总金额
        totalAmountInCents := int64(totalPayAmount * 100) // 单位为分
        appID := "wx86cbc2487aeab9fd"         // 替换为你的实际 AppID
        mchID := "1698159272"                 // 替换为你的实际商户号
    
        // 生成商户订单号
        outTradeNo := fmt.Sprintf("C%s_%s", tempOrderId, time.Now().Format("0102150405"))
        if len(outTradeNo) > 32 {
            outTradeNo = outTradeNo[:32]
        }
    
        // 确定支付描述
        orderDesc := ""
        if req.Role == "worker" {
            orderDesc = "担保系统-打手押金支付"
        } else {
            orderDesc = "担保系统-老板订单支付"
        }
    
        // 组装支付请求
        svc := jsapi.JsapiApiService{Client: client}
        prepayReq := jsapi.PrepayRequest{
            Appid:       core.String(appID),
            Mchid:       core.String(mchID),
            Description: core.String(orderDesc),
            OutTradeNo:  core.String(outTradeNo),
            NotifyUrl:   core.String("https://www.moki-flanke.icu/api/guarantee/payNotify"),
            Amount: &jsapi.Amount{
                Total:    core.Int64(totalAmountInCents),
                Currency: core.String("CNY"),
            },
            Payer: &jsapi.Payer{
                Openid: core.String(openid),
            },
        }
    
        log.Printf("[INFO] 发送担保支付统一下单请求: %+v", prepayReq)
        resp, _, err := svc.Prepay(context.Background(), prepayReq)
        if err != nil {
            log.Printf("[ERROR] 担保支付统一下单失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    5,
                "message": "支付请求失败",
            })
            return
        }
        log.Printf("[INFO] 担保支付统一下单成功: %+v", resp)
    
        // 更新临时订单支付信息 - 使用负数服务费
        _, err = db.Exec(
            `UPDATE TempGuarantees SET 
            OutTradeNo = ?, 
            PrepayID = ?,
            ServiceFee = ?,
            OriginalAmount = ?
            WHERE ID = ?`,
            outTradeNo,
            *resp.PrepayId,
            negativeServiceFee,  // 使用负数服务费
            payAmount,
            tempOrderId,
        )
        if err != nil {
            log.Printf("[WARNING] 更新临时订单支付信息失败: %v", err)
            // 尝试使用旧表结构更新
            _, err = db.Exec(
                `UPDATE TempGuarantees SET 
                OutTradeNo = ?, 
                PrepayID = ?
                WHERE ID = ?`,
                outTradeNo,
                *resp.PrepayId,
                tempOrderId,
            )
            if err != nil {
                log.Printf("[WARNING] 使用旧表结构更新临时订单支付信息也失败: %v", err)
            }
            // 继续处理
        }
    
        // 生成支付参数
        timestamp := strconv.FormatInt(time.Now().Unix(), 10)
        nonceStr := GetRandomString(32)
        packageStr := "prepay_id=" + *resp.PrepayId
    
        // 加载商户私钥
        privateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
        if err != nil {
            log.Printf("[ERROR] 加载商户私钥失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    6,
                "message": "支付请求失败",
            })
            return
        }
    
        // 拼接签名原串
        message := fmt.Sprintf("%s\n%s\n%s\n%s\n", appID, timestamp, nonceStr, packageStr)
    
        // 使用商户私钥进行签名
        signature, err := SignWithSHA256RSA(message, privateKey)
        if err != nil {
            log.Printf("[ERROR] 生成支付签名失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    7,
                "message": "支付请求失败",
            })
            return
        }
    
        // 返回支付参数
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "准备支付成功",
            "data": gin.H{
                "tempOrderId": tempOrderId,
                "timeStamp":   timestamp,
                "nonceStr":    nonceStr,
                "package":     packageStr,
                "signType":    "RSA",
                "paySign":     signature,
            },
        })
    })
    // 创建订单API - 修改后的返回值包含跳转URL
    r.POST("/api/create_order", func(c *gin.Context) {
        var orderData struct {
            InputContent string `json:"inputContent" binding:"required"` // 订单内容
            BossId       string `json:"bossId" binding:"required"`       // 老板ID
            UserOpenId   string `json:"userOpenId" binding:"required"`   // 必须提供的用户标识
        }
        
        // 解析请求体
        if err := c.BindJSON(&orderData); err != nil {
            log.Printf("API创建订单 - 请求解析错误: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "无效的请求数据", "details": err.Error()})
            return
        }
        
        log.Printf("API创建订单 - 接收到数据: %+v", orderData)
        
        // 通过userOpenId查询用户openid
        var openid string
        err := db.QueryRow("SELECT openid FROM users WHERE useropenid = ?", orderData.UserOpenId).Scan(&openid)
        if err != nil {
            log.Printf("API创建订单 - 查询用户失败: %v, userOpenId: %s", err, orderData.UserOpenId)
            c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "无效的UserOpenId，用户未找到或未授权"})
            return
        }
        
        // 验证用户权限
        var user struct {
            ID         int
            Username   string
            InviteCode *string
        }
        err = db.QueryRow("SELECT id, username, invite_code FROM users WHERE openid = ?", openid).Scan(&user.ID, &user.Username, &user.InviteCode)
        if err != nil {
            log.Printf("API创建订单 - 查询用户详情失败: %v, openid: %s", err, openid)
            c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "用户数据查询失败"})
            return
        }
        
        // 验证是否有发单权限
        if user.InviteCode == nil || *user.InviteCode != "000000" {
            log.Printf("API创建订单 - 用户 %s (%d) 无发单权限, InviteCode: %v", user.Username, user.ID, user.InviteCode)
            c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "没有发单权限"})
            return
        }
        
        log.Printf("API创建订单 - 用户 %s 已验证发单权限", user.Username)
        
        // 设置代发消息内容
        forwardMessage := orderData.InputContent + "，复制信息发我，这是代发"
        
        // 使用默认联系人
        contactUserName := "@@本人"
        log.Printf("API创建订单 - 使用默认联系人: %s", contactUserName)
        
        // 关联游戏ID
        globalGameIDMap[forwardMessage] = orderData.BossId
        
        // 创建Bridge并转发消息
        createBridge(openid, "代发", contactUserName, forwardMessage, "来个车队", 0)
        forwardMessageToAllGroupswaibu(db, forwardMessage)
        
        // 获取创建的Bridge ID
        bridge, err := findBridgeForContent(forwardMessage)
        
        if err != nil || bridge == nil {
            log.Printf("API创建订单 - 查找Bridge失败: %v", err)
            c.JSON(http.StatusOK, gin.H{
                "success": true,
                "message": "订单提交成功，但无法获取订单ID",
            })
            return
        }
        
        log.Printf("API创建订单 - 成功创建Bridge: ID=%s", bridge.ID)
        
        // 构建完整的跳转URL
        baseURL := c.Request.Host
        redirectURL := fmt.Sprintf("https://%s/boss/%s", baseURL, bridge.ID)
        
        // 返回成功响应，包含跳转URL
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "message": "订单提交成功",
            "bridgeId": bridge.ID,
            "orderTime": time.Now().Format("2006-01-02 15:04:05"),
            "bossRoute": redirectURL, 
        })
    })
    r.POST("/api/advanced_order", func(c *gin.Context) {
        var orderData struct {
            Code        string   `json:"code"`
            OrderType   string   `json:"orderType"`
            Orders      []string `json:"orders"`
            TargetRanks []string `json:"targetRanks"`
            GameName    string   `json:"gameName,omitempty"`
        }
    
        if err := c.BindJSON(&orderData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法安排，核对信息"})
            return
        }
        
        // 使用code获取openid
        openid, err := getOpenIDFromCode(orderData.Code)
        if err != nil {
            fmt.Printf("Error getting openid: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取OpenID失败", "details": err.Error()})
            return
        }
        // 验证用户权限
        var user struct {
            ID         int
            Username   string
            InviteCode *string
        }
        var balance float64
        err = db.QueryRow("SELECT id, username, invite_code, balance FROM users WHERE openid = ?", openid).Scan(&user.ID, &user.Username, &user.InviteCode, &balance)
        if err != nil {
            log.Printf("API创建订单 - 查询用户详情失败: %v, openid: %s", err, openid)
            c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "用户数据查询失败"})
            return
        }
        
        // 验证是否有发单权限
        if user.InviteCode == nil || *user.InviteCode != "000000" {
            log.Printf("API创建订单 - 用户 %s (%d) 无发单权限, InviteCode: %v", user.Username, user.ID, user.InviteCode)
            c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "没有发单权限"})
            return
        }
        // 去掉 "来个" 两个字符
        if strings.HasPrefix(orderData.OrderType, "来个") {
            orderData.OrderType = strings.TrimPrefix(orderData.OrderType, "来个")
        }
    
        // 计算所有玩家升级所需的总价格
        totalPrice, err := calculateTotalPrice(db, orderData.OrderType, orderData.TargetRanks, orderData.Orders)
        if err != nil {
            fmt.Printf("Error calculating total price: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "计算价格失败", "details": err.Error()})
            return
        }
        
        // 检查用户余额是否足够
        if balance < totalPrice {
            c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("余额不足，需要 ¥%.2f，当前余额 ¥%.2f", totalPrice, balance)})
            return
        }
    
        // 生成订单内容
        content, err := generateContent(db, orderData.Orders, orderData.OrderType, 0, orderData.TargetRanks)
        if err != nil {
            fmt.Printf("Error generating content: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "生成内容失败", "details": err.Error()})
            return
        }
        
        // 保存游戏名称到全局映射（如果提供）
        if orderData.GameName != "" {
            globalGameIDMap[content] = orderData.GameName
        }
        
        createBridge(openid, "代发", "@@本人", content, orderData.OrderType, 0)
        
        switch orderData.OrderType {
        case "车队":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupswaibu(db, content)
            }
        case "陪玩":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupspeiwan(db, content)
            }
        case "小姐姐":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupsxjj(db, content)
            }
        case "代练":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupsdailian(db, content)
            }
        }
        
        // 获取创建的Bridge ID
        bridge, err := findBridgeForContent(content)
        if err != nil || bridge == nil {
            log.Printf("API创建订单 - 查找Bridge失败: %v", err)
            c.JSON(http.StatusOK, gin.H{
                "success": true,
                "message": "订单提交成功，但无法获取订单ID",
            })
            return
        }
        
        log.Printf("API创建订单 - 成功创建Bridge: ID=%s", bridge.ID)
        
        // 构建完整的跳转URL
        baseURL := c.Request.Host
        redirectURL := fmt.Sprintf("https://%s/boss/%s?vip=1", baseURL, bridge.ID)
        
        // 返回成功响应，包含跳转URL和订单信息
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "message": "订单提交成功",
            "bridgeId": bridge.ID,
            "orderTime": time.Now().Format("2006-01-02 15:04:05"),
            "bossRoute": redirectURL,
        })
    })
    // 获取用户的userOpenId
    r.GET("/api/get-user-openid", func(c *gin.Context) {
        // 获取微信授权码
        code := c.Query("code")
        if code == "" {
            log.Printf("[ERROR] 缺少微信授权码")
            c.JSON(http.StatusBadRequest, gin.H{
                "success": false,
                "message": "缺少微信授权码",
            })
            return
        }

        // 获取OpenID
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "message": "获取用户信息失败",
            })
            return
        }

        // 查询用户的userOpenId
        var userOpenId string
        err = db.QueryRow("SELECT useropenid FROM users WHERE openid = ?", openid).Scan(&userOpenId)
        if err != nil {
            if err == sql.ErrNoRows {
                // 用户存在但没有userOpenId
                log.Printf("[INFO] 用户 %s 存在但没有userOpenId", openid)
                c.JSON(http.StatusOK, gin.H{
                    "success": true,
                    "userOpenId": "", // 返回空字符串表示未生成
                })
                return
            }
            
            log.Printf("[ERROR] 查询userOpenId失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "message": "查询用户数据失败",
            })
            return
        }

        // 返回userOpenId
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "userOpenId": userOpenId,
        })
    })

    // 生成新的userOpenId
    r.POST("/api/generate-user-openid", func(c *gin.Context) {
        // 获取微信授权码
        type GenerateRequest struct {
            Code string `json:"code"` // 微信授权码
        }
        
        var req GenerateRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("[ERROR] 解析生成userOpenId请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{
                "success": false,
                "message": "请求参数错误",
            })
            return
        }
        
        if req.Code == "" {
            log.Printf("[ERROR] 缺少微信授权码")
            c.JSON(http.StatusBadRequest, gin.H{
                "success": false,
                "message": "缺少微信授权码",
            })
            return
        }

        // 获取OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "message": "获取用户信息失败",
            })
            return
        }

        // 检查用户是否有权限生成userOpenId（是否有发单权限）
        var inviteCode string
        err = db.QueryRow("SELECT invite_code FROM users WHERE openid = ?", openid).Scan(&inviteCode)
        if err != nil {
            if err == sql.ErrNoRows {
                log.Printf("[ERROR] 用户 %s 不存在", openid)
                c.JSON(http.StatusForbidden, gin.H{
                    "success": false,
                    "message": "用户不存在",
                })
                return
            }
            
            log.Printf("[ERROR] 查询用户失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "message": "查询用户数据失败",
            })
            return
        }

        // 验证是否有发单权限
        if inviteCode != "000000" {
            log.Printf("[ERROR] 用户 %s 没有权限生成userOpenId", openid)
            c.JSON(http.StatusForbidden, gin.H{
                "success": false,
                "message": "没有权限生成API密钥",
            })
            return
        }

        // 生成新的userOpenId（使用UUID）
        newUserOpenId := uuid.New().String()

        // 更新数据库
        _, err = db.Exec("UPDATE users SET useropenid = ? WHERE openid = ?", newUserOpenId, openid)
        if err != nil {
            log.Printf("[ERROR] 更新userOpenId失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "message": "生成API密钥失败",
            })
            return
        }

        // 返回新生成的userOpenId
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "userOpenId": newUserOpenId,
            "message": "API密钥生成成功",
        })
    })
   // 确认创建担保 - 修改版
    r.POST("/api/guarantee/confirmCreate", func(c *gin.Context) {
        // 请求参数结构体
        type ConfirmCreateRequest struct {
            TempOrderId string `json:"tempOrderId"` // 临时订单ID
            Code        string `json:"code"`        // 微信授权码
            ForceCreate bool   `json:"forceCreate"` // 是否强制创建
        }

        var req ConfirmCreateRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("[ERROR] 解析确认创建请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "请求参数错误",
            })
            return
        }

        log.Printf("[INFO] 收到确认创建担保请求: %+v", req)

        // 获取 OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)

        // 查询临时订单信息 - 仅使用基本字段
        var deposit, amount float64
        var role, remark, outTradeNo string
        var tempOpenID string

        err = db.QueryRow(
            `SELECT OpenID, Deposit, Amount, Role, Remark, OutTradeNo 
            FROM TempGuarantees WHERE ID = ?`,
            req.TempOrderId,
        ).Scan(&tempOpenID, &deposit, &amount, &role, &remark, &outTradeNo)

        if err != nil {
            log.Printf("[ERROR] 查询临时订单信息失败: %v", err)
            c.JSON(http.StatusNotFound, gin.H{
                "code":    3,
                "message": "临时订单不存在或已过期",
            })
            return
        }

        // 验证OpenID是否匹配
        if tempOpenID != openid {
            log.Printf("[ERROR] OpenID不匹配: 临时订单=%s, 请求=%s", tempOpenID, openid)
            c.JSON(http.StatusUnauthorized, gin.H{
                "code":    4,
                "message": "无权操作此临时订单",
            })
            return
        }

        // 检查支付状态 - 完全依赖支付记录表
        var paymentFound bool = false
        
        // 1. 通过支付记录表检查是否有成功支付
        var records []struct {
            Status string
            OutTradeNo string
        }
        
        // 1.1 通过临时订单ID直接查询支付记录
        rows, err := db.Query(
            `SELECT Status, OutTradeNo FROM GuaranteePayments 
            WHERE GuaranteeID = ? AND Status = 'success'`,
            req.TempOrderId,
        )
        
        if err == nil {
            defer rows.Close()
            for rows.Next() {
                var record struct {
                    Status string
                    OutTradeNo string
                }
                rows.Scan(&record.Status, &record.OutTradeNo)
                records = append(records, record)
            }
        }
        
        // 1.2 通过OutTradeNo查询
        if outTradeNo != "" {
            rows, err := db.Query(
                `SELECT Status, OutTradeNo FROM GuaranteePayments 
                WHERE OutTradeNo = ? AND Status = 'success'`,
                outTradeNo,
            )
            
            if err == nil {
                defer rows.Close()
                for rows.Next() {
                    var record struct {
                        Status string
                        OutTradeNo string
                    }
                    rows.Scan(&record.Status, &record.OutTradeNo)
                    records = append(records, record)
                }
            }
        }
        
        // 1.3 通过临时订单ID前缀查询 - 重点检查这种模式
        rows, err = db.Query(
            `SELECT Status, OutTradeNo FROM GuaranteePayments 
            WHERE OutTradeNo LIKE ? AND Status = 'success'`,
            "CTEMP" + strings.TrimPrefix(req.TempOrderId, "TEMP") + "%",
        )
        
        if err == nil {
            defer rows.Close()
            for rows.Next() {
                var record struct {
                    Status string
                    OutTradeNo string
                }
                rows.Scan(&record.Status, &record.OutTradeNo)
                records = append(records, record)
            }
        }
        
        // 1.4 通过OpenID查询最近成功的支付
        rows, err = db.Query(
            `SELECT Status, OutTradeNo FROM GuaranteePayments 
            WHERE OpenID = ? AND CreateTime > datetime('now', '-30 minute') 
            AND Status = 'success'
            ORDER BY CreateTime DESC LIMIT 1`,
            openid,
        )
        
        if err == nil {
            defer rows.Close()
            for rows.Next() {
                var record struct {
                    Status string
                    OutTradeNo string
                }
                rows.Scan(&record.Status, &record.OutTradeNo)
                records = append(records, record)
            }
        }
        
        // 检查是否找到任何成功支付记录
        if len(records) > 0 {
            paymentFound = true
            // 使用第一条记录的OutTradeNo
            outTradeNo = records[0].OutTradeNo
            log.Printf("[INFO] 找到成功支付记录: %s", outTradeNo)
        }

        // 处理未找到支付记录的情况
        if !paymentFound && !req.ForceCreate {
            log.Printf("[ERROR] 支付未完成，未找到成功支付记录")
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    5,
                "message": "请先完成支付",
            })
            return
        }
        
        if !paymentFound && req.ForceCreate {
            log.Printf("[WARNING] 未找到支付记录，但用户请求强制创建")
        }

        // 生成唯一的担保ID
        guaranteeID := fmt.Sprintf("GUA%s%d", time.Now().Format("20060102"), time.Now().UnixNano()%1000000)

        // 存储担保信息到数据库
        _, err = db.Exec(
            `INSERT INTO Guarantees 
            (ID, CreatorOpenID, Deposit, Amount, CreatorRole, Status, Remark, CreateTime, CreatorPayTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            guaranteeID,
            openid,
            deposit,
            amount,
            role,
            "waiting_join", // 状态为等待加入，因为已支付
            remark,
            time.Now().Format("2006-01-02 15:04:05"),
            time.Now().Format("2006-01-02 15:04:05"), // 因为已支付，记录支付时间
        )
        if err != nil {
            log.Printf("[ERROR] 存储担保信息失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    6,
                "message": "创建担保失败",
            })
            return
        }

        // 如果有支付记录，更新支付记录关联到新创建的担保ID
        if outTradeNo != "" {
            _, err = db.Exec(
                `UPDATE GuaranteePayments SET 
                GuaranteeID = ? 
                WHERE OutTradeNo = ?`,
                guaranteeID,
                outTradeNo,
            )
            if err != nil {
                log.Printf("[WARNING] 更新支付记录关联担保ID失败: %v", err)
                // 继续处理
            }
        }
        
        // 删除临时订单 - 不再需要，已创建正式担保
        _, err = db.Exec(
            `DELETE FROM TempGuarantees WHERE ID = ?`,
            req.TempOrderId,
        )
        
        if err != nil {
            log.Printf("[WARNING] 删除临时订单失败: %v", err)
            // 继续处理
        }

        // 返回创建成功响应
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "创建担保成功",
            "data": gin.H{
                "id": guaranteeID,
            },
        })
    })
    r.POST("/api/guarantee/generatePayParams", func(c *gin.Context) {
        type PayRequest struct {
            OrderID   string  `json:"orderId"`   // 担保订单号
            Amount    float64 `json:"amount"`    // 支付金额
            Code      string  `json:"code"`      // 用户授权码
            Role      string  `json:"role"`      // 用户角色
            IsJoining bool    `json:"isJoining"` // 是否为加入担保的支付
        }
    
        var payReq PayRequest
        if err := c.ShouldBindJSON(&payReq); err != nil {
            log.Printf("[ERROR] 解析支付请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
            return
        }
        log.Printf("[INFO] 收到担保支付请求: %+v", payReq)
    
        // 计算服务费 (1%)，最低为1元
        serviceFee := payReq.Amount * 0.01
        if serviceFee < 1.0 {
            serviceFee = 1.0
        }
        
        // 计算总支付金额 (原金额 + 服务费)
        totalAmount := payReq.Amount + serviceFee
        
        log.Printf("[INFO] 计算服务费: 原金额 %.2f, 服务费 %.2f, 总额 %.2f", payReq.Amount, serviceFee, totalAmount)
    
        // 获取 OpenID
        openid, err := getOpenIDFromCode(payReq.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)
    
        // 如果是加入担保的支付，先验证用户是否有权限加入
        if payReq.IsJoining {
            // 查询担保信息
            var creatorOpenID, status string
            var participantOpenID sql.NullString
            
            err = db.QueryRow(
                `SELECT CreatorOpenID, Status, ParticipantOpenID FROM Guarantees WHERE ID = ?`,
                payReq.OrderID,
            ).Scan(&creatorOpenID, &status, &participantOpenID)
            
            if err != nil {
                log.Printf("[ERROR] 查询担保信息失败: %v", err)
                c.JSON(http.StatusNotFound, gin.H{"error": "担保订单不存在"})
                return
            }
    
            // 验证状态
            if status != "waiting_join" {
                log.Printf("[ERROR] 担保订单状态不正确: %s", status)
                c.JSON(http.StatusBadRequest, gin.H{"error": "担保订单状态不正确，无法加入"})
                return
            }
    
            // 验证是否已有参与者
            if participantOpenID.Valid && participantOpenID.String != "" {
                log.Printf("[ERROR] 担保订单已有参与者: %s", participantOpenID.String)
                c.JSON(http.StatusBadRequest, gin.H{"error": "该担保已有参与者"})
                return
            }
    
            // 验证不是创建者自己加入
            if openid == creatorOpenID {
                log.Printf("[ERROR] 创建者尝试加入自己的担保: %s", openid)
                c.JSON(http.StatusBadRequest, gin.H{"error": "不能加入自己创建的担保订单"})
                return
            }
            
            log.Printf("[INFO] 用户 %s 有权加入担保 %s", openid, payReq.OrderID)
        }
    
        // 初始化微信支付客户端
        client, err := InitWeChatPayClient()
        if err != nil {
            log.Printf("[ERROR] 初始化微信支付客户端失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
    
        // 生成支付请求
        totalAmountInCents := int64(totalAmount * 100) // 单位为分
        appID := "wx86cbc2487aeab9fd"             // 替换为你的实际 AppID
        mchID := "1698159272"                     // 替换为你的实际商户号
    
        // 查询订单获取详情
        var creatorRole string
        err = db.QueryRow("SELECT CreatorRole FROM Guarantees WHERE ID = ?", payReq.OrderID).Scan(&creatorRole)
        if err != nil {
            log.Printf("[ERROR] 查询担保订单失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
        
        // 根据支付角色决定支付描述
        var orderDesc string
        
        // 检查是否是加入担保的支付
        if payReq.IsJoining {
            // 使用传入的角色参数
            if payReq.Role == "boss" {
                orderDesc = "担保系统-订单金额支付"
            } else {
                orderDesc = "担保系统-打手押金支付"
            }
        } else {
            // 查询当前用户是否是创建者
            var creatorOpenID string
            err = db.QueryRow("SELECT CreatorOpenID FROM Guarantees WHERE ID = ?", payReq.OrderID).Scan(&creatorOpenID)
            if err != nil {
                log.Printf("[ERROR] 查询担保订单创建者失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
                return
            }
            
            if openid == creatorOpenID {
                // 创建者支付
                if creatorRole == "worker" {
                    orderDesc = "担保系统-打手押金支付"
                } else {
                    orderDesc = "担保系统-老板订单支付"
                }
            } else {
                // 加入者支付
                if creatorRole == "worker" {
                    orderDesc = "担保系统-订单金额支付"
                } else {
                    orderDesc = "担保系统-打手押金支付"
                }
            }
        }
    
        // 为交易单号添加前缀以区分是否为加入支付
        // 修改这里，确保订单号不超过32个字符
        var outTradeNo string
        guaranteeIDShort := payReq.OrderID
        if len(guaranteeIDShort) > 16 {
            // 如果担保ID太长，则截取前16个字符
            guaranteeIDShort = guaranteeIDShort[:16]
        }
        
        timestamp := time.Now().Format("0102150405") // 减少时间戳长度，只用月日时分秒
        
        if payReq.IsJoining {
            outTradeNo = "J" + guaranteeIDShort + "_" + timestamp
        } else {
            outTradeNo = "P" + guaranteeIDShort + "_" + timestamp
        }
        
        // 确保总长度不超过32
        if len(outTradeNo) > 32 {
            outTradeNo = outTradeNo[:32]
        }
        
        log.Printf("[INFO] 生成的订单号: %s, 长度: %d", outTradeNo, len(outTradeNo))
    
        svc := jsapi.JsapiApiService{Client: client}
        req := jsapi.PrepayRequest{
            Appid:       core.String(appID),
            Mchid:       core.String(mchID),
            Description: core.String(orderDesc),
            OutTradeNo:  core.String(outTradeNo),
            NotifyUrl:   core.String("https://www.moki-flanke.icu/api/guarantee/payNotify"),
            Amount: &jsapi.Amount{
                Total:    core.Int64(totalAmountInCents),
                Currency: core.String("CNY"),
            },
            Payer: &jsapi.Payer{
                Openid: core.String(openid),
            },
        }
    
        log.Printf("[INFO] 发送担保支付统一下单请求: %+v", req)
        resp, _, err := svc.Prepay(context.Background(), req)
        if err != nil {
            log.Printf("[ERROR] 担保支付统一下单失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
        log.Printf("[INFO] 担保支付统一下单成功: %+v", resp)
    
        timestamp = strconv.FormatInt(time.Now().Unix(), 10)
        nonceStr := GetRandomString(32)
        packageStr := "prepay_id=" + *resp.PrepayId
    
        // 使用第一个文件中的函数名
        privateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
        if err != nil {
            log.Printf("[ERROR] 加载商户私钥失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
    
        // 拼接签名原串
        message := fmt.Sprintf("%s\n%s\n%s\n%s\n", appID, timestamp, nonceStr, packageStr)
    
        // 使用商户私钥进行签名
        signature, err := SignWithSHA256RSA(message, privateKey)
        if err != nil {
            log.Printf("[ERROR] 生成支付签名失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
    
        // 尝试存储支付记录，处理可能的表结构问题
        var insertErr error
        
        // 第一次尝试，包含 IsJoining、Role 和 ServiceFee 字段
        _, insertErr = db.Exec(
            `INSERT INTO GuaranteePayments 
            (GuaranteeID, OpenID, Amount, ServiceFee, TradeType, OutTradeNo, PrepayID, CreateTime, IsJoining, Role) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            payReq.OrderID,
            openid,
            payReq.Amount,
            serviceFee,
            orderDesc,
            outTradeNo,
            *resp.PrepayId,
            time.Now().Format("2006-01-02 15:04:05"),
            payReq.IsJoining,
            payReq.Role,
        )
        
        if insertErr != nil {
            // 如果失败，尝试不包含 IsJoining 和 Role 字段的插入
            log.Printf("[WARNING] 使用完整字段存储支付记录失败: %v，尝试使用基本字段", insertErr)
            
            _, insertErr = db.Exec(
                `INSERT INTO GuaranteePayments 
                (GuaranteeID, OpenID, Amount, ServiceFee, TradeType, OutTradeNo, PrepayID, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
                payReq.OrderID,
                openid,
                payReq.Amount,
                serviceFee,
                orderDesc,
                outTradeNo,
                *resp.PrepayId,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if insertErr != nil {
                log.Printf("[ERROR] 存储支付记录失败: %v", insertErr)
                // 不返回错误，继续支付流程
            } else {
                log.Printf("[INFO] 成功存储基本支付记录")
            }
        } else {
            log.Printf("[INFO] 成功存储完整支付记录（包含 IsJoining、Role 和 ServiceFee）")
        }
    
        // 返回支付参数
        payParams := gin.H{
            "appId":     appID,
            "timeStamp": timestamp,
            "nonceStr":  nonceStr,
            "package":   packageStr,
            "signType":  "RSA",
            "paySign":   signature,
        }
        log.Printf("[INFO] 担保支付参数成功生成: %+v", payParams)
        c.JSON(http.StatusOK, payParams)
    })
    
    // 修改回调函数，处理支付成功后的服务费记录
    r.POST("/api/guarantee/payNotify", func(c *gin.Context) {
        ctx := context.Background()
        rawBody, _ := io.ReadAll(c.Request.Body) // 记录原始请求体
        log.Printf("[INFO] 收到担保支付回调请求: %s", string(rawBody))

        c.Request.Body = io.NopCloser(bytes.NewBuffer(rawBody)) // 重置请求体供后续解析

        apiV3Key := "MIIEKDCCAxCgAwIBAgIUUqirwt6exDMy" // 替换为你的实际密钥
        platformCertPath := "./wechatpay_cert_5714802C1232EFD19CED7478282FC8E1A088DD84.pem" // 使用正确的证书路径

        // 加载微信支付平台证书
        platformCert, err := utils.LoadCertificateWithPath(platformCertPath)
        if err != nil {
            log.Printf("[ERROR] 加载微信支付平台证书失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }

        // 创建证书访问器
        certVisitor := core.NewCertificateMapWithList([]*x509.Certificate{platformCert})

        // 使用 Verifier 初始化通知处理器
        handler := notify.NewNotifyHandler(apiV3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))

        transaction := make(map[string]interface{})
        _, err = handler.ParseNotifyRequest(ctx, c.Request, &transaction)
        if err != nil {
            log.Printf("[ERROR] 解析担保支付通知失败: %v", err)
            c.String(http.StatusBadRequest, "FAIL")
            return
        }

        log.Printf("[INFO] 担保支付回调解析成功，内容: %+v", transaction)

        // 获取订单号和支付金额
        outTradeNo, ok := transaction["out_trade_no"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 out_trade_no 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取交易ID
        transactionId, _ := transaction["transaction_id"].(string)

        // 检查是否是临时订单支付（前缀为C）
        isTempOrderPayment := strings.HasPrefix(outTradeNo, "CTEMP")
        
        // 从订单号中提取临时订单ID或担保ID
        var orderID string
        if isTempOrderPayment {
            // 提取临时订单ID
            parts := strings.Split(outTradeNo, "_")
            if len(parts) >= 1 {
                orderID = parts[0][1:] // 去掉C前缀
                log.Printf("[INFO] 解析到临时订单ID: %s", orderID)
            } else {
                orderID = strings.TrimPrefix(outTradeNo, "C")
                log.Printf("[INFO] 解析到临时订单ID(备用方式): %s", orderID)
            }
        } else {
            // 处理正常担保订单
            if strings.HasPrefix(outTradeNo, "J") || strings.HasPrefix(outTradeNo, "P") {
                parts := strings.Split(outTradeNo, "_")
                if len(parts) >= 1 {
                    orderID = parts[0][1:] // 去掉J或P前缀
                    log.Printf("[INFO] 解析到担保ID: %s", orderID)
                } else {
                    // 兼容旧格式
                    orderID = outTradeNo
                    if idx := strings.Index(outTradeNo, "_"); idx > 0 {
                        orderID = outTradeNo[:idx]
                    }
                    orderID = strings.TrimPrefix(orderID, "J")
                    orderID = strings.TrimPrefix(orderID, "P")
                    log.Printf("[INFO] 解析到担保ID(备用方式): %s", orderID)
                }
            } else {
                orderID = outTradeNo
                log.Printf("[INFO] 无法识别订单号前缀，使用完整订单号: %s", orderID)
            }
        }

        // 获取支付者OpenID
        payerOpenID, ok := transaction["payer"].(map[string]interface{})["openid"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 payer.openid 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取支付金额
        amountMap, ok := transaction["amount"].(map[string]interface{})
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 amount 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        totalFee, ok := amountMap["payer_total"].(float64)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 payer_total 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 从数据库查询预先计算的服务费
        var serviceFee float64
        var originalAmount float64
        
        err = db.QueryRow(
            `SELECT Amount, ServiceFee FROM GuaranteePayments WHERE OutTradeNo = ?`,
            outTradeNo,
        ).Scan(&originalAmount, &serviceFee)
        
        // 如果查询失败，则使用默认的服务费计算方式
        if err != nil {
            log.Printf("[WARNING] 查询预设服务费失败: %v, 将使用默认计算方式", err)
            // 计算服务费 (1%)
            serviceFee = totalFee * 0.01 / 100.0 // 转换为元
            // 确保最低服务费为1元
            if serviceFee < 1.0 {
                serviceFee = 1.0
            }
            originalAmount = totalFee/100.0 - serviceFee
        }
        
        // 服务费为负数 - 修改点4
        negativeServiceFee := -math.Abs(serviceFee)
        
        log.Printf("[INFO] 支付金额: %.2f 元, 服务费: %.2f 元, 实际金额: %.2f 元", 
                totalFee/100, serviceFee, originalAmount)
        
        // 生成唯一的交易ID
        transactionUUID := uuid.New().String()
        
        // 1. 首先更新支付记录表
        result, err := db.Exec(
            `UPDATE GuaranteePayments SET 
            Status = ?, 
            TransactionID = ?,
            PayTime = ?
            WHERE OutTradeNo = ?`,
            "success",
            transactionId,
            time.Now().Format("2006-01-02 15:04:05"),
            outTradeNo,
        )
        
        rowsAffected := int64(0)
        if err == nil {
            rowsAffected, _ = result.RowsAffected()
        }
        
        // 2. 如果没有找到记录进行更新，则插入新记录
        if err != nil || rowsAffected == 0 {
            log.Printf("[INFO] 未找到支付记录进行更新，创建新记录: %v", err)
            
            // 获取PrepayID，尽量避免NULL约束失败
            prepayID := ""
            // 尝试查询TempGuarantees表获取PrepayID
            if isTempOrderPayment {
                err = db.QueryRow(
                    `SELECT PrepayID FROM TempGuarantees WHERE ID = ?`,
                    orderID,
                ).Scan(&prepayID)
                
                if err != nil {
                    prepayID = "unknown_" + time.Now().Format("20060102150405") // 提供一个默认值防止NULL约束
                    log.Printf("[WARNING] 获取PrepayID失败: %v, 使用默认值", err)
                }
            }
            
            _, err = db.Exec(
                `INSERT INTO GuaranteePayments 
                (GuaranteeID, OpenID, Amount, ServiceFee, TradeType, OutTradeNo, PrepayID, TransactionID, Status, CreateTime, PayTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                orderID, // 使用解析出的ID
                payerOpenID,
                originalAmount, // 原始金额，不含服务费
                negativeServiceFee, // 服务费（负数）- 修改点
                "担保系统支付",
                outTradeNo,
                prepayID, // 提供PrepayID值，避免NULL约束错误
                transactionId,
                "success",
                time.Now().Format("2006-01-02 15:04:05"),
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                log.Printf("[WARNING] 创建支付记录失败: %v", err)
            } else {
                log.Printf("[INFO] 成功创建支付记录")
            }
        } else {
            // 更新服务费为负值 - 修改点5
            _, err = db.Exec(
                `UPDATE GuaranteePayments SET 
                ServiceFee = ?
                WHERE OutTradeNo = ?`,
                negativeServiceFee,
                outTradeNo,
            )
            if err != nil {
                log.Printf("[WARNING] 更新支付记录的服务费为负值失败: %v", err)
            }
            log.Printf("[INFO] 成功更新支付记录状态为成功: %s", outTradeNo)
        }
        negativeTotalFee := -math.Abs(float64(totalFee)/100.0)
        // 3. 添加用户交易记录
        _, err = db.Exec(
            `INSERT INTO UserTransactions 
            (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            transactionUUID,
            payerOpenID,
            "担保支付",
            negativeTotalFee, // 总支付金额（元）
            negativeServiceFee, // 服务费（负数）- 修改点
            originalAmount, // 实际金额（元）
            "success",
            orderID,
            transactionId,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            log.Printf("[WARNING] 创建用户交易记录失败: %v", err)
        } else {
            log.Printf("[INFO] 成功创建用户交易记录: %s", transactionUUID)
        }
        
        // 4. 添加服务费记录
        serviceFeesUUID := uuid.New().String()
        _, err = db.Exec(
            `INSERT INTO ServiceFees 
            (ID, TransactionID, GuaranteeID, Type, Amount, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?)`,
            serviceFeesUUID,
            transactionId,
            orderID,
            "担保支付服务费",
            negativeServiceFee, // 服务费（负数）- 修改点
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            log.Printf("[WARNING] 创建服务费记录失败: %v", err)
        } else {
            log.Printf("[INFO] 成功创建服务费记录: %s", serviceFeesUUID)
        }
        
        // 5. 添加用户服务费记录
        userFeesUUID := uuid.New().String()
        _, err = db.Exec(
            `INSERT INTO UserFees 
            (ID, OpenID, FeeType, Amount, RelatedTransactionID, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?)`,
            userFeesUUID,
            payerOpenID,
            "担保支付服务费",
            negativeServiceFee, // 服务费（负数）- 修改点
            transactionUUID,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            log.Printf("[WARNING] 创建用户服务费记录失败: %v", err)
        } else {
            log.Printf("[INFO] 成功创建用户服务费记录: %s", userFeesUUID)
        }
        
        // 6. 如果是临时订单支付，更新临时订单状态
        if isTempOrderPayment {
            _, err = db.Exec(
                `UPDATE TempGuarantees SET 
                OutTradeNo = ?,
                PayStatus = ?,
                ServiceFee = ?
                WHERE ID = ?`,
                outTradeNo,
                "success",
                negativeServiceFee, // 服务费（负数）- 修改点
                orderID,
            )
            
            if err != nil {
                log.Printf("[WARNING] 更新临时订单支付状态失败: %v", err)
                
                // 尝试只更新OutTradeNo
                _, err = db.Exec(
                    `UPDATE TempGuarantees SET 
                    OutTradeNo = ?
                    WHERE ID = ?`,
                    outTradeNo,
                    orderID,
                )
                
                if err != nil {
                    log.Printf("[WARNING] 更新临时订单OutTradeNo失败: %v", err)
                } else {
                    log.Printf("[INFO] 成功更新临时订单OutTradeNo: %s", orderID)
                }
            } else {
                log.Printf("[INFO] 成功更新临时订单支付状态: %s", orderID)
            }
        }

        // 回复微信支付平台
        c.String(http.StatusOK, "SUCCESS")
        log.Printf("[INFO] 担保支付通知处理成功，订单号: %s，金额: %.2f 元，服务费: %.2f 元", 
                outTradeNo, totalFee/100, negativeServiceFee)
    })

    r.POST("/api/guarantee/join", func(c *gin.Context) {
        type JoinRequest struct {
            GuaranteeID string `json:"guaranteeId"` // 担保ID
            Code        string `json:"code"`        // 微信授权码
            Role        string `json:"role"`        // 选择的角色
            IsPaid      bool   `json:"isPaid"`      // 是否已支付
        }

        var req JoinRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("[ERROR] 解析加入担保请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "请求参数错误",
            })
            return
        }
        log.Printf("[INFO] 收到加入担保请求: %+v", req)

        // 获取 OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        log.Printf("[INFO] 获取用户OpenID成功: %s", openid)

        // 查询担保信息
        var creatorOpenID, status string
        var participantOpenID sql.NullString
        
        err = db.QueryRow(
            `SELECT CreatorOpenID, Status, ParticipantOpenID FROM Guarantees WHERE ID = ?`,
            req.GuaranteeID,
        ).Scan(&creatorOpenID, &status, &participantOpenID)
        
        if err != nil {
            log.Printf("[ERROR] 查询担保信息失败: %v", err)
            c.JSON(http.StatusNotFound, gin.H{
                "code":    3,
                "message": "担保订单不存在",
            })
            return
        }
        log.Printf("[INFO] 担保订单信息：创建者=%s, 状态=%s", creatorOpenID, status)

        // 验证状态
        if status != "waiting_join" {
            log.Printf("[ERROR] 担保订单状态不正确: %s", status)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    4,
                "message": "担保订单状态不正确，无法加入",
            })
            return
        }

        // 验证是否已有参与者
        if participantOpenID.Valid && participantOpenID.String != "" {
            log.Printf("[ERROR] 担保订单已有参与者: %s", participantOpenID.String)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    6,
                "message": "该担保已有参与者",
            })
            return
        }

        // 验证不是创建者自己加入
        if openid == creatorOpenID {
            log.Printf("[ERROR] 创建者尝试加入自己的担保: %s", openid)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    5,
                "message": "不能加入自己创建的担保订单",
            })
            return
        }

        // 如果已经支付，则更新担保状态
        var statusUpdate, timeField string
        var participantPayTime interface{} = nil

        // 添加参与者信息
        statusUpdate = status // 默认状态不变
        
        // 如果已支付，则更新参与者支付时间
        if req.IsPaid {
            participantPayTime = time.Now().Format("2006-01-02 15:04:05")
            
            // 查询创建者是否已支付
            var creatorPayTimeValue sql.NullString
            err = db.QueryRow(
                "SELECT CreatorPayTime FROM Guarantees WHERE ID = ?", 
                req.GuaranteeID,
            ).Scan(&creatorPayTimeValue)
            
            if err != nil {
                log.Printf("[ERROR] 查询创建者支付时间失败: %v", err)
            } else if creatorPayTimeValue.Valid && creatorPayTimeValue.String != "" {
                // 如果创建者已支付，且参与者也已支付，则更新状态为processing
                statusUpdate = "processing"
                log.Printf("[INFO] 创建者和参与者都已支付，更新状态为processing")
            }
            
            timeField = ", ParticipantPayTime = ?"
        } else {
            timeField = ""
        }

        // 更新担保订单
        var updateQuery string
        var updateArgs []interface{}
        
        if req.IsPaid {
            updateQuery = "UPDATE Guarantees SET ParticipantOpenID = ?, Status = ?" + timeField + " WHERE ID = ?"
            updateArgs = []interface{}{openid, statusUpdate, participantPayTime, req.GuaranteeID}
        } else {
            updateQuery = "UPDATE Guarantees SET ParticipantOpenID = ?, Status = ? WHERE ID = ?"
            updateArgs = []interface{}{openid, statusUpdate, req.GuaranteeID}
        }
        
        _, err = db.Exec(updateQuery, updateArgs...)
        if err != nil {
            log.Printf("[ERROR] 更新担保参与者信息失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    8,
                "message": "加入担保失败",
            })
            return
        }
        log.Printf("[INFO] 已将用户 %s 添加为担保 %s 的参与者", openid, req.GuaranteeID)

        var responseMsg string
        if req.IsPaid {
            responseMsg = "加入担保并支付成功"
        } else {
            responseMsg = "加入担保成功，请继续支付"
        }

        // 返回成功响应
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": responseMsg,
        })
    })

    r.POST("/api/guarantee/complete", func(c *gin.Context) {
        type CompleteRequest struct {
            GuaranteeId string `json:"guaranteeId"` // 担保ID
            Code        string `json:"code"`        // 微信授权码
        }
    
        var req CompleteRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("[ERROR] 解析完成担保请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "请求参数错误",
            })
            return
        }
    
        log.Printf("[INFO] 收到完成担保请求: %+v", req)
    
        // 获取 OpenID
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)
    
        // 查询担保信息
        var deposit, amount float64
        var creatorOpenID, participantOpenID, status, creatorRole string
        var trxResult sql.Result
    
        err = db.QueryRow(
            `SELECT CreatorOpenID, ParticipantOpenID, Deposit, Amount, Status, CreatorRole
            FROM Guarantees WHERE ID = ?`,
            req.GuaranteeId,
        ).Scan(&creatorOpenID, &participantOpenID, &deposit, &amount, &status, &creatorRole)
    
        if err != nil {
            log.Printf("[ERROR] 查询担保信息失败: %v", err)
            c.JSON(http.StatusNotFound, gin.H{
                "code":    3,
                "message": "担保订单不存在",
            })
            return
        }
    
        // 验证是否为老板操作
        var bossOpenID string
        if creatorRole == "boss" {
            bossOpenID = creatorOpenID
        } else {
            if participantOpenID == "" {
                log.Printf("[ERROR] 担保订单无参与者")
                c.JSON(http.StatusBadRequest, gin.H{
                    "code":    4,
                    "message": "担保订单尚未有参与者",
                })
                return
            }
            bossOpenID = participantOpenID
        }
    
        if openid != bossOpenID {
            log.Printf("[ERROR] 只有老板才能完成担保: 请求者=%s, 老板=%s", openid, bossOpenID)
            c.JSON(http.StatusUnauthorized, gin.H{
                "code":    5,
                "message": "只有老板才能完成担保",
            })
            return
        }
    
        // 验证订单状态
        if status != "processing" {
            log.Printf("[ERROR] 担保订单状态不正确: %s", status)
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    6,
                "message": "担保订单状态不正确，无法完成",
            })
            return
        }
    
        // 开始数据库事务
        tx, err := db.Begin()
        if err != nil {
            log.Printf("[ERROR] 开始数据库事务失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    7,
                "message": "系统错误",
            })
            return
        }
        defer func() {
            if err != nil {
                tx.Rollback()
                log.Printf("[INFO] 回滚事务")
            }
        }()
    
        // 1. 更新担保状态
        trxResult, err = tx.Exec(
            `UPDATE Guarantees SET 
            Status = ?, 
            CompleteTime = ? 
            WHERE ID = ?`,
            "completed",
            time.Now().Format("2006-01-02 15:04:05"),
            req.GuaranteeId,
        )
        if err != nil {
            log.Printf("[ERROR] 更新担保状态失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    8,
                "message": "完成担保失败",
            })
            return
        }
    
        // 确定打手OpenID
        var workerOpenID string
        if creatorRole == "worker" {
            workerOpenID = creatorOpenID
        } else {
            workerOpenID = participantOpenID
        }
    
        // 查询是否有退款
        var totalRefundAmount float64
        err = tx.QueryRow(
            `SELECT COALESCE(SUM(RefundAmount), 0) 
            FROM GuaranteeRefunds 
            WHERE GuaranteeID = ? AND Status = 'success'`,
            req.GuaranteeId,
        ).Scan(&totalRefundAmount)
        
        if err != nil && err != sql.ErrNoRows {
            log.Printf("[ERROR] 查询退款记录失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    9,
                "message": "查询退款记录失败",
            })
            return
        }
        
        // 计算打手应得金额（扣除退款和服务费）
        // 1. 先计算扣除退款后的金额
        amountAfterRefund := amount - totalRefundAmount
        if amountAfterRefund < 0 {
            amountAfterRefund = 0
        }
        
        serviceFee := amountAfterRefund * 0.02
        if serviceFee < 1 && amountAfterRefund > 0 {
            serviceFee = 1
        }
        
        // 3. 最终金额
        finalAmount := amountAfterRefund - serviceFee
        if finalAmount < 0 {
            finalAmount = 0
        }
        
        log.Printf("[INFO] 打手应得金额计算: 原始金额=%.2f, 退款金额=%.2f, 扣退款后=%.2f, 服务费=%.2f, 最终金额=%.2f", 
                    amount, totalRefundAmount, amountAfterRefund, serviceFee, finalAmount)
    
        // 2. 增加打手余额
        log.Printf("[INFO] 给打手(%s)加款: %.2f元", workerOpenID, finalAmount)
        trxResult, err = tx.Exec(
            `UPDATE users SET 
            balance = balance + ? 
            WHERE openid = ?`,
            finalAmount,
            workerOpenID,
        )
        if err != nil {
            log.Printf("[ERROR] 更新打手余额失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    10,
                "message": "加款失败",
            })
            return
        }
        // 添加一笔担保获得的交易记录 - 只记录最终金额，不涉及服务费
        transactionUUID := uuid.New().String()
        _, err = tx.Exec(
            `INSERT INTO UserTransactions 
            (ID, OpenID, TransactionType, Amount, Status, RelatedOrderID, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?)`,
            transactionUUID,
            workerOpenID,
            "担保获得",
            finalAmount,             // 直接使用最终金额（已扣除服务费）
            "成功",
            req.GuaranteeId,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        rowsAffected, _ := trxResult.RowsAffected()
        if rowsAffected == 0 {
            // 用户不存在，创建用户记录
            log.Printf("[INFO] 打手用户不存在，创建新用户记录")
            _, err = tx.Exec(
                `INSERT INTO users (openid, balance) VALUES (?, ?)`,
                workerOpenID,
                finalAmount,
            )
            if err != nil {
                log.Printf("[ERROR] 创建打手用户记录失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{
                    "code":    11,
                    "message": "创建用户记录失败",
                })
                return
            }
        }
        
        // 记录服务费
        _, err = tx.Exec(
            `INSERT INTO ServiceFees 
            (GuaranteeID, Type, Amount, CreateTime) 
            VALUES (?, ?, ?, ?)`,
            req.GuaranteeId,
            "completion_fee",
            serviceFee,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            log.Printf("[WARNING] 记录服务费失败: %v", err)
            // 继续执行，不影响后续流程
        }
    
        // 3. 查询押金支付信息，准备退款
        var payRecord struct {
            OutTradeNo    string
            TransactionID string
            Amount        float64
            ServiceFee    float64 // 添加服务费字段
        }
        
        // 查询交易记录，同时获取服务费
        err = tx.QueryRow(
            `SELECT OutTradeNo, TransactionID, Amount, COALESCE(ServiceFee, 0) as ServiceFee
            FROM GuaranteePayments 
            WHERE GuaranteeID = ? AND OpenID = ? AND Status = 'success'
            ORDER BY CreateTime DESC LIMIT 1`,
            req.GuaranteeId,
            workerOpenID,
        ).Scan(&payRecord.OutTradeNo, &payRecord.TransactionID, &payRecord.Amount, &payRecord.ServiceFee)
        
        if err != nil {
            // 尝试不带服务费查询
            err = tx.QueryRow(
                `SELECT OutTradeNo, TransactionID, Amount, 0 as ServiceFee
                FROM GuaranteePayments 
                WHERE GuaranteeID = ? AND OpenID = ? AND Status = 'success'
                ORDER BY CreateTime DESC LIMIT 1`,
                req.GuaranteeId,
                workerOpenID,
            ).Scan(&payRecord.OutTradeNo, &payRecord.TransactionID, &payRecord.Amount, &payRecord.ServiceFee)
            
            if err != nil {
                log.Printf("[WARNING] 未找到打手支付记录: %v", err)
                // 继续执行，不影响后续流程
            } else {
                log.Printf("[INFO] 找到打手支付记录(无服务费): %+v", payRecord)
            }
        } else {
            log.Printf("[INFO] 找到打手支付记录(含服务费): %+v", payRecord)
        }
    
        // 提交事务
        err = tx.Commit()
        if err != nil {
            log.Printf("[ERROR] 提交事务失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    12,
                "message": "系统错误",
            })
            return
        }
    
        // 4. 发起微信退款，退还押金和服务费
        if payRecord.TransactionID != "" && payRecord.Amount > 0 {
            // 计算总退款金额 = 押金 + 服务费
            totalRefundAmount := deposit - payRecord.ServiceFee
            log.Printf("[INFO] 发起退款: 押金=%.2f, 服务费=%.2f, 总退款=%.2f", 
                      deposit, payRecord.ServiceFee, totalRefundAmount)
            
            go initiateWechatRefund(payRecord.TransactionID, payRecord.OutTradeNo, totalRefundAmount, "担保完成退还押金及服务费")
        }
    
        // 返回成功响应
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "担保交易已完成",
            "data": gin.H{
                "originalAmount": amount,
                "refundAmount": totalRefundAmount,
                "serviceFee": serviceFee,
                "finalAmount": finalAmount,
                "depositRefund": deposit,
                "serviceRefund": payRecord.ServiceFee,
                "totalRefund": deposit + payRecord.ServiceFee,
            },
        })
    })
	// 取消担保接口
	r.POST("/api/guarantee/cancel", func(c *gin.Context) {
		type CancelRequest struct {
			GuaranteeID string `json:"guaranteeId"` // 担保ID
		}

		var req CancelRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			log.Printf("[ERROR] 解析取消担保请求参数失败: %v", err)
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    1,
				"message": "请求参数错误",
			})
			return
		}

		// 获取当前用户OpenID (假设通过中间件已经获取)
		currentOpenID := c.GetString("openid")
		if currentOpenID == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    2,
				"message": "未登录或会话已过期",
			})
			return
		}

		// 查询担保信息
		var creatorOpenID, status string
		err := db.QueryRow(
			`SELECT CreatorOpenID, Status FROM Guarantees WHERE ID = ?`,
			req.GuaranteeID,
		).Scan(&creatorOpenID, &status)
		if err != nil {
			log.Printf("[ERROR] 查询担保信息失败: %v", err)
			c.JSON(http.StatusNotFound, gin.H{
				"code":    3,
				"message": "担保订单不存在",
			})
			return
		}

		// 验证状态，只有等待加入的订单可以取消
		if status != StatusWaitingJoin {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    4,
				"message": "只有等待加入的担保订单才能取消",
			})
			return
		}

		// 验证是否有权限操作（只有创建者可以取消）
		if currentOpenID != creatorOpenID {
			c.JSON(http.StatusForbidden, gin.H{
				"code":    5,
				"message": "只有创建者才能取消担保订单",
			})
			return
		}

		// 更新担保状态为已取消
		_, err = db.Exec(
			`UPDATE Guarantees SET 
			Status = ?, 
			CancelTime = ? 
			WHERE ID = ?`,
			StatusCancelled,
			time.Now().Format("2006-01-02 15:04:05"),
			req.GuaranteeID,
		)
		if err != nil {
			log.Printf("[ERROR] 更新担保状态失败: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    6,
				"message": "取消担保失败",
			})
			return
		}

		// TODO: 处理退款逻辑
		// 将已支付的款项退还给创建者

		// 返回成功响应
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "担保已取消",
		})
	})

	r.GET("/api/guarantee/list", func(c *gin.Context) {
        // 从请求中获取code
        code := c.GetHeader("X-WX-Code")
        if code == "" {
            c.JSON(http.StatusUnauthorized, gin.H{
                "code":    1,
                "message": "缺少授权信息",
            })
            return
        }
        
        // 使用现有方法获取OpenID
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        
        // 查询用户相关的担保订单
        rows, err := db.Query(
            `SELECT 
                ID, CreatorOpenID, ParticipantOpenID, Deposit, Amount, 
                CreatorRole, Status, Remark, CreateTime 
            FROM Guarantees 
            WHERE CreatorOpenID = ? OR ParticipantOpenID = ?
            ORDER BY CreateTime DESC`,
            openid, openid,
        )
        if err != nil {
            log.Printf("[ERROR] 查询担保列表失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取列表失败",
            })
            return
        }
        defer rows.Close()
    
        var guarantees []gin.H
        for rows.Next() {
            var id, creatorOpenID, creatorRole, status, remark, createTime string
            var participantOpenID sql.NullString
            var deposit, amount float64
    
            err := rows.Scan(
                &id, &creatorOpenID, &participantOpenID, &deposit, &amount,
                &creatorRole, &status, &remark, &createTime,
            )
            if err != nil {
                log.Printf("[ERROR] 扫描担保记录失败: %v", err)
                continue
            }
    
            // 确定当前用户在订单中的角色
            var role string
            if openid == creatorOpenID {
                role = creatorRole
            } else {
                // 如果创建者是打手，参与者就是老板
                if creatorRole == RoleWorker {
                    role = RoleBoss
                } else {
                    role = RoleWorker
                }
            }
    
            guarantees = append(guarantees, gin.H{
                "id":        id,
                "deposit":   deposit,
                "amount":    amount,
                "role":      role,
                "status":    status,
                "remark":    remark,
                "createTime": createTime,
            })
        }
    
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "获取列表成功",
            "data":    guarantees,
        })
    })
    // 担保详情接口
    r.GET("/api/guarantee/detail", func(c *gin.Context) {
        // 打印请求信息
        log.Printf("[INFO] 收到担保详情请求: %s", c.Request.URL.String())
        
        id := c.Query("id")
        log.Printf("[DEBUG] 担保ID: %s", id)
        
        if id == "" {
            log.Printf("[ERROR] 缺少担保ID参数")
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "缺少担保ID",
            })
            return
        }
        if strings.HasPrefix(id, "id=") {
            id = id[3:] // 去除"id="前缀
        }        
        // 获取微信code
        code := c.Query("code")
        log.Printf("[DEBUG] 获取到的微信code: %s", code)
        
        if code == "" {
            log.Printf("[ERROR] 缺少微信登录code参数")
            c.JSON(http.StatusBadRequest, gin.H{
                "code":    1,
                "message": "缺少微信登录code",
            })
            return
        }

        // 使用code获取OpenID
        log.Printf("[INFO] 开始通过code获取OpenID")
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        log.Printf("[INFO] 成功获取OpenID: %s", openid)

        // 查询担保详情
        log.Printf("[INFO] 开始查询担保详情，ID: %s", id)
        
        var guarantee gin.H
        var creatorOpenID, creatorRole, status, remark, createTime string
        var participantOpenID, creatorPayTime, participantPayTime, completeTime, cancelTime sql.NullString
        var deposit, amount float64
        
        err = db.QueryRow(
            `SELECT 
                CreatorOpenID, ParticipantOpenID, Deposit, Amount, 
                CreatorRole, Status, Remark, CreateTime,
                CreatorPayTime, ParticipantPayTime, CompleteTime, CancelTime 
            FROM Guarantees 
            WHERE ID = ?`, 
            id,
        ).Scan(
            &creatorOpenID, &participantOpenID, &deposit, &amount,
            &creatorRole, &status, &remark, &createTime,
            &creatorPayTime, &participantPayTime, &completeTime, &cancelTime,
        )
        
        if err != nil {
            if err == sql.ErrNoRows {
                log.Printf("[ERROR] 担保记录不存在，ID: %s", id)
                c.JSON(http.StatusNotFound, gin.H{
                    "code":    3,
                    "message": "担保记录不存在",
                })
                return
            }
            
            log.Printf("[ERROR] 查询担保详情失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    4,
                "message": "获取详情失败",
            })
            return
        }

        // 判断参与者角色是否已存在
        hasParticipant := participantOpenID.Valid && participantOpenID.String != ""
        log.Printf("[DEBUG] 参与者是否存在: %v", hasParticipant)
        
        // 确定当前用户在订单中的角色与权限
        var role string
        var canComplete, canCancel, canJoin bool
        var defaultJoinRole string  // 默认加入角色
        
        // 根据创建者角色确定默认加入角色
        if creatorRole == "boss" {
            defaultJoinRole = "worker"
            log.Printf("[DEBUG] 创建者为老板，默认加入角色为打手")
        } else if creatorRole == "worker" {
            defaultJoinRole = "boss"
            log.Printf("[DEBUG] 创建者为打手，默认加入角色为老板")
        }
        
        // 设置可用角色数组
        var availableRoles []string
        
        // 检查用户是否是创建者
        if openid == creatorOpenID {
            log.Printf("[DEBUG] 用户是创建者")
            role = creatorRole
            // 老板可以完成交易，任何创建者可以取消等待加入的订单
            canComplete = (role == "boss" && status == "processing")
            canCancel = (status == "waiting_join")
            canJoin = false
            availableRoles = []string{}  // 创建者不需要选择角色
        } else if participantOpenID.Valid && openid == participantOpenID.String {
            // 检查用户是否是参与者
            log.Printf("[DEBUG] 用户是参与者")
            // 如果创建者是打手，参与者就是老板
            if creatorRole == "worker" {
                role = "boss"
                // 老板可以完成交易
                canComplete = (status == "processing")
            } else {
                role = "worker"
                canComplete = false
            }
            canCancel = false
            canJoin = false
            availableRoles = []string{}  // 参与者不需要选择角色
        } else {
            // 用户既不是创建者也不是参与者
            log.Printf("[DEBUG] 用户既不是创建者也不是参与者")
            
            // 允许加入除了已完成和已取消的担保
            if status != "completed" && status != "cancelled" {
                if !hasParticipant {
                    // 如果没有参与者，则根据创建者角色分配默认角色
                    role = defaultJoinRole
                    log.Printf("[INFO] 允许用户以默认角色 %s 加入担保", role)
                    canComplete = false
                    canCancel = false
                    canJoin = true
                    // 对于默认加入，只提供预设的角色
                    availableRoles = []string{defaultJoinRole}
                } else {
                    // 如果已有参与者，则作为访客
                    role = "visitor"
                    log.Printf("[INFO] 担保已有参与者，用户作为访客查看")
                    canComplete = false
                    canCancel = false
                    canJoin = false
                    // 作为访客，可以选择任意角色
                    availableRoles = []string{"boss", "worker"}
                }
            } else {
                log.Printf("[ERROR] 担保状态是已完成或已取消，不允许加入: %s", status)
                c.JSON(http.StatusForbidden, gin.H{
                    "code":    5,
                    "message": "您无权查看此担保详情",
                })
                return
            }
        }

        log.Printf("[INFO] 用户角色: %s, 可完成: %v, 可取消: %v, 可加入: %v", 
                role, canComplete, canCancel, canJoin)
        log.Printf("[DEBUG] 默认加入角色: %s, 可用角色: %v", defaultJoinRole, availableRoles)

        // 构建响应数据
        guarantee = gin.H{
            "id":           id,
            "deposit":      deposit,
            "amount":       amount,
            "role":         role,
            "status":       status,
            "remark":       remark,
            "createTime":   createTime,
            "canComplete":  canComplete,
            "canCancel":    canCancel,
            "canJoin":      canJoin,
            "availableRoles": availableRoles,
            "defaultJoinRole": defaultJoinRole,  // 添加默认加入角色
        }

        // 添加可能存在的时间字段
        if creatorPayTime.Valid {
            guarantee["creatorPayTime"] = creatorPayTime.String
        }
        if participantPayTime.Valid {
            guarantee["participantPayTime"] = participantPayTime.String
        }
        if completeTime.Valid {
            guarantee["completeTime"] = completeTime.String
        }
        if cancelTime.Valid {
            guarantee["cancelTime"] = cancelTime.String
        }

        // 添加参与者信息（如果有）
        guarantee["hasParticipant"] = hasParticipant
        if hasParticipant {
            log.Printf("[DEBUG] 担保已有参与者: %s", participantOpenID.String)
        } else {
            log.Printf("[DEBUG] 担保没有参与者")
        }

        log.Printf("[INFO] 成功构建担保详情响应")
        c.JSON(http.StatusOK, gin.H{
            "code":    0,
            "message": "获取详情成功",
            "data":    guarantee,
        })
    })

	// 搜索担保接口
	r.GET("/api/guarantee/search", func(c *gin.Context) {
		keyword := c.Query("keyword")
		
		// 获取当前用户OpenID (假设通过中间件已经获取)
		currentOpenID := c.GetString("openid")
		if currentOpenID == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    1,
				"message": "未登录或会话已过期",
			})
			return
		}

		// 如果是ID格式的搜索，直接查询指定ID
		if strings.HasPrefix(keyword, "GUA") {
			var id, creatorOpenID, creatorRole, status, remark, createTime string
			var participantOpenID sql.NullString
			var deposit, amount float64
			
			err := db.QueryRow(
				`SELECT 
					ID, CreatorOpenID, ParticipantOpenID, Deposit, Amount, 
					CreatorRole, Status, Remark, CreateTime
				FROM Guarantees 
				WHERE ID = ?`, 
				keyword,
			).Scan(
				&id, &creatorOpenID, &participantOpenID, &deposit, &amount,
				&creatorRole, &status, &remark, &createTime,
			)
			
			if err != nil {
				if err == sql.ErrNoRows {
					// 没有找到结果，返回空数组
					c.JSON(http.StatusOK, gin.H{
						"code":    0,
						"message": "搜索成功",
						"data":    []gin.H{},
					})
					return
				}
				
				log.Printf("[ERROR] 搜索担保记录失败: %v", err)
				c.JSON(http.StatusInternalServerError, gin.H{
					"code":    2,
					"message": "搜索失败",
				})
				return
			}

			// 确定用户与该担保的关系
			var role string
			var canJoin bool
			
			if currentOpenID == creatorOpenID {
				role = creatorRole
				canJoin = false // 创建者不能加入自己的担保
			} else if participantOpenID.Valid && currentOpenID == participantOpenID.String {
				// 已经是参与者
				if creatorRole == RoleWorker {
					role = RoleBoss
				} else {
					role = RoleWorker
				}
				canJoin = false
			} else {
				// 不是创建者也不是参与者
				role = "" // 未参与
				canJoin = (status == StatusWaitingJoin) // 只有等待加入的担保可以加入
			}

			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"message": "搜索成功",
				"data": []gin.H{
					{
						"id":        id,
						"deposit":   deposit,
						"amount":    amount,
						"role":      role,
						"status":    status,
						"remark":    remark,
						"createTime": createTime,
						"canJoin":   canJoin,
					},
				},
			})
			return
		}
		
		// 常规关键词搜索，只搜索用户自己的担保
		query := `
			SELECT 
				ID, CreatorOpenID, ParticipantOpenID, Deposit, Amount, 
				CreatorRole, Status, Remark, CreateTime
			FROM Guarantees 
			WHERE (CreatorOpenID = ? OR ParticipantOpenID = ?) 
				AND (ID LIKE ? OR Remark LIKE ?) 
			ORDER BY CreateTime DESC
		`
		
		searchKey := "%" + keyword + "%"
		rows, err := db.Query(query, currentOpenID, currentOpenID, searchKey, searchKey)
		if err != nil {
			log.Printf("[ERROR] 搜索担保记录失败: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    2,
				"message": "搜索失败",
			})
			return
		}
		defer rows.Close()

		var guarantees []gin.H
		for rows.Next() {
			var id, creatorOpenID, creatorRole, status, remark, createTime string
			var participantOpenID sql.NullString
			var deposit, amount float64

			err := rows.Scan(
				&id, &creatorOpenID, &participantOpenID, &deposit, &amount,
				&creatorRole, &status, &remark, &createTime,
			)
			if err != nil {
				log.Printf("[ERROR] 扫描担保记录失败: %v", err)
				continue
			}

			// 确定当前用户在订单中的角色
			var role string
			if currentOpenID == creatorOpenID {
				role = creatorRole
			} else {
				// 如果创建者是打手，参与者就是老板
				if creatorRole == RoleWorker {
					role = RoleBoss
				} else {
					role = RoleWorker
				}
			}

			guarantees = append(guarantees, gin.H{
				"id":        id,
				"deposit":   deposit,
				"amount":    amount,
				"role":      role,
				"status":    status,
				"remark":    remark,
				"createTime": createTime,
				"canJoin":   false, // 自己的担保不能加入
			})
		}

		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "搜索成功",
			"data":    guarantees,
		})
	})
   // Bridge订单支付处理 - 优先使用余额，余额不足时使用微信支付
    r.POST("/api/bridge/pay", func(c *gin.Context) {
        type BridgePayRequest struct {
            OrderID string  `json:"orderId"` // Bridge订单号
            Amount  float64 `json:"amount"`  // 支付金额
            Code    string  `json:"code"`    // 用户授权码
        }

        var payReq BridgePayRequest
        if err := c.ShouldBindJSON(&payReq); err != nil {
            log.Printf("[ERROR] 解析Bridge支付请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
            return
        }
        log.Printf("[INFO] 收到Bridge支付请求: %+v", payReq)

        // 获取 OpenID
        openid, err := getOpenIDFromCode(payReq.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)

        // 查询用户余额
        var username string
        var userBalance float64
        
        err = db.QueryRow("SELECT username, balance FROM users WHERE openid = ?", openid).Scan(&username, &userBalance)
        if err != nil {
            log.Printf("[ERROR] 查询用户信息失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户余额失败"})
            return
        }
        
        log.Printf("[INFO] 用户 %s 当前余额: %.2f, 订单金额: %.2f", username, userBalance, payReq.Amount)
        
        // 判断用户余额是否足够支付
        if userBalance >= payReq.Amount {
            // 余额足够，使用余额支付
            log.Printf("[INFO] 用户余额充足，使用余额支付")
            
            // 开始事务
            tx, err := db.Begin()
            if err != nil {
                log.Printf("[ERROR] 开始事务失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 扣减用户余额
            _, err = tx.Exec("UPDATE users SET balance = balance - ? WHERE username = ?", 
                            payReq.Amount, username)
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 扣减用户余额失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 更新UnsettledBridges表的状态
            _, err = tx.Exec("UPDATE UnsettledBridges SET IsSettled = TRUE, SettlementTime = ? WHERE ID = ?", 
                            time.Now().Format("2006-01-02 15:04:05"), payReq.OrderID)
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 更新UnsettledBridges状态失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 获取Bridge订单的WeChatUsername（接收款项的用户）
            var weChatUsername string
            err = tx.QueryRow("SELECT WeChatUsername FROM Bridges WHERE ID = ?", payReq.OrderID).Scan(&weChatUsername)
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 获取WeChatUsername失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 查询接收方是否已注册
            var receiverOpenID string
            var receiverExists bool = true
            err = tx.QueryRow("SELECT openid FROM users WHERE wechatname = ?", weChatUsername).Scan(&receiverOpenID)
            if err != nil {
                if err == sql.ErrNoRows {
                    // 用户不存在，将使用临时表记录
                    receiverExists = false
                    log.Printf("[INFO] 接收方用户 %s 未注册，将使用临时表记录", weChatUsername)
                } else {
                    tx.Rollback()
                    log.Printf("[ERROR] 查询接收方用户失败: %v", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                    return
                }
            }
            
            // 生成唯一的交易ID
            transactionUUID := uuid.New().String()
            
            if receiverExists {
                // 用户存在，直接增加余额
                _, err = tx.Exec("UPDATE users SET balance = balance + ? WHERE openid = ?", 
                                payReq.Amount, receiverOpenID)
                if err != nil {
                    tx.Rollback()
                    log.Printf("[ERROR] 更新接收方余额失败: %v", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                    return
                }
                
                // 插入交易记录 - 收款方（已注册用户）
                receiverTransactionUUID := uuid.New().String()
                _, err = tx.Exec(
                    `INSERT INTO UserTransactions 
                    (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    receiverTransactionUUID,
                    receiverOpenID,
                    "桥接订单收款",
                    payReq.Amount, // 正数表示收入
                    0,            // 服务费
                    payReq.Amount, // 实际金额
                    "成功",
                    payReq.OrderID,
                    "balance_" + transactionUUID, // 使用与付款方相同的内部交易ID
                    time.Now().Format("2006-01-02 15:04:05"),
                )
                
                if err != nil {
                    tx.Rollback()
                    log.Printf("[ERROR] 插入收款方交易记录失败: %v", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                    return
                }
                
                // 尝试发送WebSocket通知更新余额 - 收款方
                notifyBalanceUpdate(receiverOpenID)
            } else {
                // 用户不存在，记录到临时表
                // 先检查临时表中是否已存在该用户
                var existingBalance float64
                err = tx.QueryRow("SELECT Balance FROM TempUserBalances WHERE WeChatUsername = ?", weChatUsername).Scan(&existingBalance)
                
                if err != nil {
                    if err == sql.ErrNoRows {
                        // 临时表中不存在，插入新记录
                        _, err = tx.Exec(
                            "INSERT INTO TempUserBalances (WeChatUsername, Balance, LastUpdateTime) VALUES (?, ?, ?)",
                            weChatUsername,
                            payReq.Amount,
                            time.Now().Format("2006-01-02 15:04:05"),
                        )
                    } else {
                        tx.Rollback()
                        log.Printf("[ERROR] 查询临时表失败: %v", err)
                        c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                        return
                    }
                } else {
                    // 临时表中已存在，更新余额
                    _, err = tx.Exec(
                        "UPDATE TempUserBalances SET Balance = Balance + ?, LastUpdateTime = ? WHERE WeChatUsername = ?",
                        payReq.Amount,
                        time.Now().Format("2006-01-02 15:04:05"),
                        weChatUsername,
                    )
                }
                
                if err != nil {
                    tx.Rollback()
                    log.Printf("[ERROR] 更新临时表失败: %v", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                    return
                }
                
                log.Printf("[INFO] 已将金额 %.2f 记录到用户 %s 的临时余额中", payReq.Amount, weChatUsername)
            }
            
            // 插入交易记录 - 付款方
            _, err = tx.Exec(
                `INSERT INTO UserTransactions 
                (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                transactionUUID,
                openid,
                "桥接订单支付",
                -payReq.Amount, // 负数表示支出
                0,             // 服务费
                -payReq.Amount, // 实际金额
                "成功",
                payReq.OrderID,
                "balance_" + transactionUUID, // 使用余额支付的内部交易ID
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 插入付款方交易记录失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 提交事务
            if err = tx.Commit(); err != nil {
                log.Printf("[ERROR] 提交事务失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理支付失败"})
                return
            }
            
            // 尝试发送WebSocket通知更新余额 - 付款方
            notifyBalanceUpdate(openid)
            
            // 返回成功响应
            c.JSON(http.StatusOK, gin.H{
                "code": 0,
                "message": "支付成功",
                "payType": "balance",
                "remainBalance": userBalance - payReq.Amount,
            })
            
            return
        }
        
        // 余额不足，生成微信支付参数
        log.Printf("[INFO] 用户余额不足，生成微信支付参数")

        // 初始化微信支付客户端
        client, err := InitWeChatPayClient()
        if err != nil {
            log.Printf("[ERROR] 初始化微信支付客户端失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 生成支付请求
        amountInCents := int64(payReq.Amount * 100) // 单位为分
        appID := "wx86cbc2487aeab9fd"             // 替换为你的实际 AppID
        mchID := "1698159272"                     // 替换为你的实际商户号

        svc := jsapi.JsapiApiService{Client: client}
        req := jsapi.PrepayRequest{
            Appid:       core.String(appID),
            Mchid:       core.String(mchID),
            Description: core.String("桥接订单支付"),
            OutTradeNo:  core.String(payReq.OrderID),
            NotifyUrl:   core.String("https://www.moki-flanke.icu/api/bridge/notify"),
            Amount: &jsapi.Amount{
                Total:    core.Int64(amountInCents),
                Currency: core.String("CNY"),
            },
            Payer: &jsapi.Payer{
                Openid: core.String(openid),
            },
        }

        log.Printf("[INFO] 发送统一下单请求: %+v", req)
        resp, _, err := svc.Prepay(context.Background(), req)
        if err != nil {
            log.Printf("[ERROR] 统一下单失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
        log.Printf("[INFO] 统一下单成功: %+v", resp)

        // 生成支付参数
        timestamp := strconv.FormatInt(time.Now().Unix(), 10)
        nonceStr := GetRandomString(32)
        packageStr := "prepay_id=" + *resp.PrepayId

        privateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
        if err != nil {
            log.Printf("[ERROR] 加载商户私钥失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 拼接签名原串
        message := fmt.Sprintf("%s\n%s\n%s\n%s\n", appID, timestamp, nonceStr, packageStr)

        // 使用商户私钥进行签名
        signature, err := SignWithSHA256RSA(message, privateKey)
        if err != nil {
            log.Printf("[ERROR] 生成支付签名失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 确认UnsettledBridges记录存在
        var count int
        err = db.QueryRow("SELECT COUNT(*) FROM UnsettledBridges WHERE ID = ?", payReq.OrderID).Scan(&count)
        if err != nil {
            log.Printf("[ERROR] 查询UnsettledBridges失败: %v", err)
        } else if count == 0 {
            log.Printf("[WARNING] UnsettledBridges中未找到记录ID=%s，可能需要创建", payReq.OrderID)
        }

        // 返回支付参数
        payParams := gin.H{
            "code": 1, // 1表示需要微信支付
            "message": "余额不足，请使用微信支付",
            "payType": "wechat",
            "payParams": gin.H{
                "appId":     appID,
                "timeStamp": timestamp,
                "nonceStr":  nonceStr,
                "package":   packageStr,
                "signType":  "RSA",
                "paySign":   signature,
            },
        }
        log.Printf("[INFO] 支付参数成功生成: %+v", payParams)
        c.JSON(http.StatusOK, payParams)
    })

   // Bridge订单支付回调处理
    r.POST("/api/bridge/notify", func(c *gin.Context) {
        ctx := context.Background()
        rawBody, _ := io.ReadAll(c.Request.Body) // 记录原始请求体
        log.Printf("[INFO] 收到Bridge支付回调请求: %s", string(rawBody))

        c.Request.Body = io.NopCloser(bytes.NewBuffer(rawBody)) // 重置请求体供后续解析

        apiV3Key := "MIIEKDCCAxCgAwIBAgIUUqirwt6exDMy" // 替换为你的实际密钥
        platformCertPath := "./wechatpay_cert_5714802C1232EFD19CED7478282FC8E1A088DD84.pem" // 使用正确的证书路径

        // 加载微信支付平台证书
        platformCert, err := utils.LoadCertificateWithPath(platformCertPath)
        if err != nil {
            log.Printf("[ERROR] 加载微信支付平台证书失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }

        // 创建证书访问器
        certVisitor := core.NewCertificateMapWithList([]*x509.Certificate{platformCert})

        // 使用 Verifier 初始化通知处理器
        handler := notify.NewNotifyHandler(apiV3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))

        transaction := make(map[string]interface{})
        _, err = handler.ParseNotifyRequest(ctx, c.Request, &transaction)
        if err != nil {
            log.Printf("[ERROR] 解析支付通知失败: %v", err)
            c.String(http.StatusBadRequest, "FAIL")
            return
        }

        log.Printf("[INFO] 支付回调解析成功，内容: %+v", transaction)

        // 获取订单号和支付金额
        outTradeNo, ok := transaction["out_trade_no"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 out_trade_no 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取支付者OpenID
        payerOpenID, ok := transaction["payer"].(map[string]interface{})["openid"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 payer.openid 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取支付金额
        amountMap, ok := transaction["amount"].(map[string]interface{})
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 amount 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        totalFee, ok := amountMap["total"].(float64)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 total 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取交易ID
        transactionId, _ := transaction["transaction_id"].(string)
        
        log.Printf("[INFO] Bridge订单支付金额: %.2f 元", totalFee/100)
        
        // 开始事务
        tx, err := db.Begin()
        if err != nil {
            log.Printf("[ERROR] 开始事务失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 更新Bridge订单状态为已完成
        _, err = tx.Exec("UPDATE Bridges SET IsCompleted = TRUE WHERE ID = ?", outTradeNo)
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 更新Bridge订单状态失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 更新UnsettledBridges表的状态
        _, err = tx.Exec("UPDATE UnsettledBridges SET IsSettled = TRUE, SettlementTime = ? WHERE ID = ?", 
                        time.Now().Format("2006-01-02 15:04:05"), outTradeNo)
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 更新UnsettledBridges状态失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 获取Bridge订单的WeChatUsername（接收款项的用户）
        var weChatUsername string
        err = tx.QueryRow("SELECT WeChatUsername FROM Bridges WHERE ID = ?", outTradeNo).Scan(&weChatUsername)
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 获取WeChatUsername失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 查询接收方是否已注册
        var receiverOpenID string
        var receiverExists bool = true
        err = tx.QueryRow("SELECT openid FROM users WHERE wechatname = ?", weChatUsername).Scan(&receiverOpenID)
        if err != nil {
            if err == sql.ErrNoRows {
                // 用户不存在，将使用临时表记录
                receiverExists = false
                log.Printf("[INFO] 接收方用户 %s 未注册，将使用临时表记录", weChatUsername)
            } else {
                tx.Rollback()
                log.Printf("[ERROR] 查询接收方用户失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
        }
        
        // 计算实际金额（元）
        amount := totalFee / 100.0
        
        // 生成唯一的交易ID
        transactionUUID := uuid.New().String()
        
        if receiverExists {
            // 用户存在，直接增加余额
            _, err = tx.Exec("UPDATE users SET balance = balance + ? WHERE openid = ?", 
                            amount, receiverOpenID)
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 更新接收方余额失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
            
            // 插入交易记录 - 收款方（已注册用户）
            receiverTransactionUUID := uuid.New().String()
            _, err = tx.Exec(
                `INSERT INTO UserTransactions 
                (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                receiverTransactionUUID,
                receiverOpenID,
                "桥接订单收款",
                amount, // 正数表示收入
                0,      // 服务费
                amount, // 实际金额
                "成功",
                outTradeNo,
                transactionId,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 插入收款方交易记录失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
            
            // 尝试发送WebSocket通知更新余额 - 收款方
            notifyBalanceUpdate(receiverOpenID)
        } else {
            // 用户不存在，记录到临时表
            // 先检查临时表中是否已存在该用户
            var existingBalance float64
            err = tx.QueryRow("SELECT Balance FROM TempUserBalances WHERE WeChatUsername = ?", weChatUsername).Scan(&existingBalance)
            
            if err != nil {
                if err == sql.ErrNoRows {
                    // 临时表中不存在，插入新记录
                    _, err = tx.Exec(
                        "INSERT INTO TempUserBalances (WeChatUsername, Balance, LastUpdateTime) VALUES (?, ?, ?)",
                        weChatUsername,
                        amount,
                        time.Now().Format("2006-01-02 15:04:05"),
                    )
                } else {
                    tx.Rollback()
                    log.Printf("[ERROR] 查询临时表失败: %v", err)
                    c.String(http.StatusInternalServerError, "FAIL")
                    return
                }
            } else {
                // 临时表中已存在，更新余额
                _, err = tx.Exec(
                    "UPDATE TempUserBalances SET Balance = Balance + ?, LastUpdateTime = ? WHERE WeChatUsername = ?",
                    amount,
                    time.Now().Format("2006-01-02 15:04:05"),
                    weChatUsername,
                )
            }
            
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 更新临时表失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
            
            log.Printf("[INFO] 已将金额 %.2f 记录到用户 %s 的临时余额中", amount, weChatUsername)
        }
        
        // 插入交易记录 - 付款方
        _, err = tx.Exec(
            `INSERT INTO UserTransactions 
            (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            transactionUUID,
            payerOpenID,
            "桥接订单支付",
            -amount, // 负数表示支出
            0,       // 服务费
            -amount, // 实际金额
            "成功",
            outTradeNo,
            transactionId,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 插入付款方交易记录失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 提交事务
        if err = tx.Commit(); err != nil {
            log.Printf("[ERROR] 提交事务失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 获取用户微信昵称用于通知
        var weChatUser string
        err = db.QueryRow("SELECT WeChatUser FROM Bridges WHERE ID = ?", outTradeNo).Scan(&weChatUser)
        if err != nil {
            log.Printf("[ERROR] 获取 WeChatUser 失败: %v", err)
            // 不返回错误，继续处理
        }

        // 发送消息通知
        if weChatUser != "" {
            // 查找用户昵称
            userName, err := findUserNameByNickName(weChatUser)
            if err != nil {
                log.Printf("[ERROR] 查找用户失败: %v", err)
            } else {
                // 发送结算确认消息
                content := fmt.Sprintf("桥接订单[%s]支付成功，金额:%.2f元", outTradeNo, amount)
                sendTextMessage(content, userName)
            }
        } else {
            log.Printf("[INFO] 订单 %s 未关联 WeChatUser", outTradeNo)
        }

        // 回复微信支付平台
        c.String(http.StatusOK, "SUCCESS")
        log.Printf("[INFO] Bridge支付通知处理成功，订单号: %s，金额: %.2f 元", outTradeNo, amount)
    })

    // 账户充值 - 生成支付参数
    r.POST("/api/recharge/generatePayParams", func(c *gin.Context) {
        type RechargeRequest struct {
            Amount  float64 `json:"amount"`  // 充值金额
            Code    string  `json:"code"`    // 用户授权码
        }

        var rechargeReq RechargeRequest
        if err := c.ShouldBindJSON(&rechargeReq); err != nil {
            log.Printf("[ERROR] 解析充值请求参数失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
            return
        }
        
        if rechargeReq.Amount <= 0 {
            c.JSON(http.StatusBadRequest, gin.H{"error": "充值金额必须大于0"})
            return
        }
        
        log.Printf("[INFO] 收到充值请求: %.2f元", rechargeReq.Amount)

        // 获取 OpenID
        openid, err := getOpenIDFromCode(rechargeReq.Code)
        if err != nil {
            log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
            return
        }
        log.Printf("[INFO] 获取 OpenID 成功: %s", openid)

        // 生成唯一的充值订单ID
        rechargeOrderId := "R" + time.Now().Format("20060102150405") + GetRandomString(6)
        
        // 计算服务费 (1%)
        serviceFee := rechargeReq.Amount * 0.01
        // 确保最低服务费为1元
        if serviceFee < 1.0 {
            serviceFee = 1.0
        }
        // 总支付金额 (原金额 + 服务费)
        totalAmount := rechargeReq.Amount + serviceFee
        
        log.Printf("[INFO] 充值交易，收取服务费: %.2f 元, 原始金额: %.2f 元, 总金额: %.2f 元", 
                serviceFee, rechargeReq.Amount, totalAmount)

        // 初始化微信支付客户端
        client, err := InitWeChatPayClient()
        if err != nil {
            log.Printf("[ERROR] 初始化微信支付客户端失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 生成支付请求，使用总金额（包含服务费）
        totalAmountInCents := int64(totalAmount * 100) // 单位为分
        appID := "wx86cbc2487aeab9fd"             // 替换为你的实际 AppID
        mchID := "1698159272"                     // 替换为你的实际商户号

        svc := jsapi.JsapiApiService{Client: client}
        req := jsapi.PrepayRequest{
            Appid:       core.String(appID),
            Mchid:       core.String(mchID),
            Description: core.String("账户充值"),
            OutTradeNo:  core.String(rechargeOrderId),
            NotifyUrl:   core.String("https://www.moki-flanke.icu/api/recharge/notify"),
            Amount: &jsapi.Amount{
                Total:    core.Int64(totalAmountInCents),
                Currency: core.String("CNY"),
            },
            Payer: &jsapi.Payer{
                Openid: core.String(openid),
            },
        }

        log.Printf("[INFO] 发送统一下单请求: %+v", req)
        resp, _, err := svc.Prepay(context.Background(), req)
        if err != nil {
            log.Printf("[ERROR] 统一下单失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }
        log.Printf("[INFO] 统一下单成功: %+v", resp)

        // 生成支付参数
        timestamp := strconv.FormatInt(time.Now().Unix(), 10)
        nonceStr := GetRandomString(32)
        packageStr := "prepay_id=" + *resp.PrepayId

        privateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
        if err != nil {
            log.Printf("[ERROR] 加载商户私钥失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 拼接签名原串
        message := fmt.Sprintf("%s\n%s\n%s\n%s\n", appID, timestamp, nonceStr, packageStr)

        // 使用商户私钥进行签名
        signature, err := SignWithSHA256RSA(message, privateKey)
        if err != nil {
            log.Printf("[ERROR] 生成支付签名失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "支付请求失败"})
            return
        }

        // 将充值信息记录到UnsettledBridges表中（复用现有表结构）
        _, err = db.Exec(
            "INSERT INTO UnsettledBridges (ID, OriginalAmount, ServiceFee, IsSettled) VALUES (?, ?, ?, ?)",
            rechargeOrderId, rechargeReq.Amount, serviceFee, 0,
        )
        
        if err != nil {
            log.Printf("[WARNING] 插入充值记录失败: %v", err)
            // 继续处理，不返回错误
        } else {
            log.Printf("[INFO] 成功插入充值记录到UnsettledBridges表")
        }

        // 返回支付参数
        payParams := gin.H{
            "appId":     appID,
            "timeStamp": timestamp,
            "nonceStr":  nonceStr,
            "package":   packageStr,
            "signType":  "RSA",
            "paySign":   signature,
            "orderId":   rechargeOrderId,
            "serviceFee": serviceFee,
            "actualAmount": rechargeReq.Amount,
            "totalAmount": totalAmount,
        }
        log.Printf("[INFO] 充值支付参数成功生成: %+v", payParams)
        c.JSON(http.StatusOK, payParams)
    })

    // 充值支付回调处理
    r.POST("/api/recharge/notify", func(c *gin.Context) {
        ctx := context.Background()
        rawBody, _ := io.ReadAll(c.Request.Body) // 记录原始请求体
        log.Printf("[INFO] 收到充值支付回调请求: %s", string(rawBody))

        c.Request.Body = io.NopCloser(bytes.NewBuffer(rawBody)) // 重置请求体供后续解析

        apiV3Key := "MIIEKDCCAxCgAwIBAgIUUqirwt6exDMy" // 替换为你的实际密钥
        platformCertPath := "./wechatpay_cert_5714802C1232EFD19CED7478282FC8E1A088DD84.pem" // 使用正确的证书路径

        // 加载微信支付平台证书
        platformCert, err := utils.LoadCertificateWithPath(platformCertPath)
        if err != nil {
            log.Printf("[ERROR] 加载微信支付平台证书失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }

        // 创建证书访问器
        certVisitor := core.NewCertificateMapWithList([]*x509.Certificate{platformCert})

        // 使用 Verifier 初始化通知处理器
        handler := notify.NewNotifyHandler(apiV3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))

        transaction := make(map[string]interface{})
        _, err = handler.ParseNotifyRequest(ctx, c.Request, &transaction)
        if err != nil {
            log.Printf("[ERROR] 解析支付通知失败: %v", err)
            c.String(http.StatusBadRequest, "FAIL")
            return
        }

        log.Printf("[INFO] 支付回调解析成功，内容: %+v", transaction)

        // 获取订单号和支付金额
        outTradeNo, ok := transaction["out_trade_no"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 out_trade_no 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 验证订单前缀是否为充值订单
        if !strings.HasPrefix(outTradeNo, "R") {
            log.Printf("[ERROR] 非充值订单通过充值回调接口处理: %s", outTradeNo)
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取支付者OpenID
        payerOpenID, ok := transaction["payer"].(map[string]interface{})["openid"].(string)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 payer.openid 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取支付金额
        amountMap, ok := transaction["amount"].(map[string]interface{})
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 amount 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        totalFee, ok := amountMap["total"].(float64)
        if !ok {
            log.Printf("[ERROR] 支付通知中缺少 total 字段或类型错误")
            c.Status(http.StatusBadRequest)
            return
        }

        // 获取交易ID
        transactionId, _ := transaction["transaction_id"].(string)
        
        log.Printf("[INFO] 充值支付金额: %.2f 元", totalFee/100)
        
        // 从UnsettledBridges表中获取充值记录
        var originalAmount, serviceFee float64
        
        err = db.QueryRow(
            `SELECT OriginalAmount, ServiceFee FROM UnsettledBridges WHERE ID = ?`,
            outTradeNo,
        ).Scan(&originalAmount, &serviceFee)
        
        // 如果查询失败，使用默认计算方式
        if err != nil {
            log.Printf("[WARNING] 查询充值记录失败: %v, 将使用默认计算方式", err)
            
            // 计算服务费 (1%)
            serviceFee = totalFee * 0.01 / 100.0 // 转换为元
            // 确保最低服务费为1元
            if serviceFee < 1.0 {
                serviceFee = 1.0
            }
            // 实际金额 (扣除服务费)
            originalAmount = totalFee/100.0 - serviceFee
        }
        
        log.Printf("[INFO] 充值交易，服务费: %.2f 元, 原始金额: %.2f 元, 总额: %.2f 元", 
                serviceFee, originalAmount, totalFee/100)
        
        // 开始事务
        tx, err := db.Begin()
        if err != nil {
            log.Printf("[ERROR] 开始事务失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 更新UnsettledBridges表的状态
        _, err = tx.Exec("UPDATE UnsettledBridges SET IsSettled = 1 WHERE ID = ?", outTradeNo)
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 更新UnsettledBridges状态失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }

        // 生成唯一的交易ID
        transactionUUID := uuid.New().String()
        
        // 服务费为负数
        negativeServiceFee := -math.Abs(serviceFee)
        
        // 插入交易记录
        _, err = tx.Exec(
            `INSERT INTO UserTransactions 
            (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            transactionUUID,
            payerOpenID,
            "充值",
            totalFee / 100.0,   // 总支付金额，转换为元
            negativeServiceFee, // 服务费（负数）
            originalAmount,     // 原始金额（不含服务费）
            "成功",
            outTradeNo,
            transactionId,
            time.Now().Format("2006-01-02 15:04:05"),
        )
        
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 插入交易记录失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 记录服务费
        if serviceFee > 0 {
            // 生成服务费记录ID
            userFeesUUID := uuid.New().String()
            
            // 插入用户服务费记录 - 使用负数
            _, err = tx.Exec(
                `INSERT INTO UserFees 
                (ID, OpenID, FeeType, Amount, RelatedTransactionID, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?)`,
                userFeesUUID,
                payerOpenID,
                "充值服务费",
                negativeServiceFee, // 负数服务费
                transactionUUID,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 记录用户服务费失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
            
            // 记录服务费到ServiceFees表 - 使用负数
            _, err = tx.Exec(
                `INSERT INTO ServiceFees 
                (TransactionID, Type, Amount, CreateTime) 
                VALUES (?, ?, ?, ?)`,
                transactionId,
                "充值服务费",
                negativeServiceFee, // 负数服务费
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[WARNING] 记录服务费到ServiceFees表失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
        }
        
        // 查询用户信息
        var username string
        err = tx.QueryRow("SELECT username FROM users WHERE openid = ?", payerOpenID).Scan(&username)
        
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 查询用户username失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 更新用户余额
        _, err = tx.Exec(
            `UPDATE users SET balance = balance + ? WHERE username = ?`,
            originalAmount, // 原始金额（不含服务费）
            username,
        )
        
        if err != nil {
            tx.Rollback()
            log.Printf("[ERROR] 更新用户余额失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        // 检查充值金额是否大于500，如果是则开启权限
        if originalAmount > 500 {
            // 检查用户是否已经有权限
            var currentInviteCode *string
            err := tx.QueryRow("SELECT invite_code FROM users WHERE username = ?", username).Scan(&currentInviteCode)
            
            if err != nil {
                tx.Rollback()
                log.Printf("[ERROR] 查询用户权限状态失败: %v", err)
                c.String(http.StatusInternalServerError, "FAIL")
                return
            }
            
            // 如果用户没有权限或不是管理权限，则授予权限
            if currentInviteCode == nil || *currentInviteCode != "000000" {
                _, err = tx.Exec(`UPDATE users SET invite_code = '000000' WHERE username = ?`, username)
                
                if err != nil {
                    tx.Rollback()
                    log.Printf("[ERROR] 开启用户权限失败: %v", err)
                    c.String(http.StatusInternalServerError, "FAIL")
                    return
                }
                
                log.Printf("[INFO] 用户 %s 充值金额 %.2f 元大于500元，已开启发单权限", username, originalAmount)
            } else {
                log.Printf("[INFO] 用户 %s 已拥有发单权限，无需重复开启", username)
            }
        }
        
        // 提交事务
        if err = tx.Commit(); err != nil {
            log.Printf("[ERROR] 提交事务失败: %v", err)
            c.String(http.StatusInternalServerError, "FAIL")
            return
        }
        
        log.Printf("[INFO] 成功添加用户余额: %.2f 元", originalAmount)
        
        // 尝试发送WebSocket通知更新余额
        notifyBalanceUpdate(payerOpenID)
        
        // 回复微信支付平台
        c.String(http.StatusOK, "SUCCESS")
        log.Printf("[INFO] 充值支付通知处理成功，订单号: %s，总金额: %.2f 元，服务费: %.2f 元，实际金额: %.2f 元", 
            outTradeNo, totalFee/100, serviceFee, originalAmount)
    })

    r.GET("/get-price-list", func(c *gin.Context) {
        // 查询 ID 为 13 的事件内容
        query := `SELECT event_title, event_text FROM current_event WHERE id = ?`
        var eventTitle, eventText string
    
        // 执行查询
        err := db.QueryRow(query, 13).Scan(&eventTitle, &eventText)
        if err != nil {
            if err == sql.ErrNoRows {
                // 如果未找到记录
                log.Println("未找到 ID 为 13 的事件记录")
                c.JSON(http.StatusNotFound, gin.H{"error": "未找到对应的事件记录"})
            } else {
                // 查询出错
                log.Printf("查询事件记录时出错: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取事件内容"})
            }
            return
        }
        c.JSON(http.StatusOK, gin.H{
            "event_title": eventTitle,
            "event_text":  eventText,
        })
        log.Println("事件数据成功返回给客户端")
    })
    
    r.POST("/get_display_data", func(c *gin.Context) {
        // 接收前端发送的 code
        var requestData struct {
            Code string `json:"code"`
        }
        if err := c.ShouldBindJSON(&requestData); err != nil {
            log.Printf("解析请求数据失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
            return
        }
    
        // 模拟通过 code 获取 openid 的逻辑
        openid, err := getOpenIDFromCode(requestData.Code)
        if err != nil {
            log.Printf("获取 openid 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取 openid"})
            return
        }
    
        // 更新 Expenditures 表中 OpenID 为空的记录
        defaultOpenID := "o_zrB61MeaAOLXIo09ougNwc9Rio"
        _, err = db.Exec(`UPDATE Expenditures SET OpenID = ? WHERE OpenID IS NULL`, defaultOpenID)
        if err != nil {
            log.Printf("更新支出表中的空 OpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新支出表失败"})
            return
        }
    
        // 查询 friends 表 (不是 contacts 表)
        rows, err := db.Query("SELECT id, userName, nickName, remark, bigHeadImgUrl FROM friends")
        if err != nil {
            log.Printf("查询friends表时出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取联系人数据"})
            return
        }
        defer rows.Close()
    
        // 添加更多日志
        log.Printf("开始查询friends表")
    
        var friends []gin.H
        for rows.Next() {
            var id int
            var userName, nickName string
            var remark sql.NullString      // Handle NULL remarks
            var bigHeadImgUrl sql.NullString  // Handle NULL avatar URLs
            
            if err := rows.Scan(&id, &userName, &nickName, &remark, &bigHeadImgUrl); err != nil {
                log.Printf("扫描数据库结果时出错: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
            
            // Get actual avatar URL (empty string if NULL)
            avatarUrl := ""
            if bigHeadImgUrl.Valid {
                avatarUrl = bigHeadImgUrl.String
                
                // Validate avatar URL if not empty
                if avatarUrl != "" && !strings.HasPrefix(avatarUrl, "http") {
                    log.Printf("警告: 用户[%s]的头像URL不是有效的URL格式", nickName)
                    // Use default avatar if URL is invalid
                    avatarUrl = "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
                }
            }
            
            // Only add friends with a valid and non-empty remark
            if remark.Valid && remark.String != "" {
                friends = append(friends, gin.H{
                    "ID":           id,
                    "UserName":     userName,
                    "NickName":     nickName,
                    "Remark":       remark.String,
                    "BigHeadImgUrl": avatarUrl,
                    "AvatarUrl":    avatarUrl,
                })
            }
        }
        // 查询 Bridges 表
        bridgeRows, err := db.Query(`
            SELECT ID, 
                   COALESCE(WeChatUser, '') AS WeChatUser, 
                   COALESCE(Msg, '') AS Msg, 
                   COALESCE(GameID, '') AS GameID, 
                   COALESCE(Stars, 0) AS Stars, 
                   COALESCE(GroupUserNickName, '') AS GroupUserNickName, 
                   COALESCE(CreatedAt, '') AS CreatedAt
            FROM Bridges
            WHERE GroupID = ?`, openid) // 使用 openid 作为过滤条件
        if err != nil {
            log.Printf("查询 Bridges 表失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取 Bridges 数据"})
            return
        }
        defer bridgeRows.Close()
    
        var bridges []gin.H
        for bridgeRows.Next() {
            var id, weChatUser, msg, gameID, groupUserNickName, createdAt string
            var stars int
            if err := bridgeRows.Scan(&id, &weChatUser, &msg, &gameID, &stars, &groupUserNickName, &createdAt); err != nil {
                log.Printf("扫描 Bridges 表结果失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
    
            // 查询好友 ID 是否匹配 GroupUserNickName
            var friendID int
            err := db.QueryRow(`
                SELECT id
                FROM friends
                WHERE userName = ?`,
                groupUserNickName,
            ).Scan(&friendID)
            if err != nil && err != sql.ErrNoRows {
                log.Printf("查询好友 ID 失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
    
            // 查询 Expenditures 表中的 Payment
            var payment int
            err = db.QueryRow(`
                SELECT COALESCE(SUM(Payment), 0)
                FROM Expenditures
                WHERE BridgeID = ?`, id).Scan(&payment)
            if err != nil && err != sql.ErrNoRows {
                log.Printf("查询 Payment 失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
    
            // 查询 UnsettledBridges 表中的 IsSettled
            var isSettled bool
            err = db.QueryRow(`
                SELECT IsSettled
                FROM UnsettledBridges
                WHERE ID = ?`, id).Scan(&isSettled)
            if err != nil && err != sql.ErrNoRows {
                log.Printf("查询 IsSettled 失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
    
            // 将数据加入 bridges 列表
            bridges = append(bridges, gin.H{
                "ID":                id,
                "WeChatUser":        weChatUser,
                "Msg":               msg,
                "GameID":            gameID,
                "Stars":             stars,
                "FriendID":          friendID,
                "CreatedAt":         createdAt,
                "Payment":           payment,   // 总支付金额
                "IsSettled":         isSettled, // 是否结算
            })
        }
    
        // 如果没有桥梁数据，返回空数组
        if len(bridges) == 0 {
            bridges = []gin.H{}
        }
    
      // 查询发单排行
        expenditureRows, err := db.Query(`
        SELECT 
            u.name AS UserName, 
            COALESCE(SUM(e.Payment), 0) AS TotalPayment, 
            COUNT(*) AS TotalCount, 
            COUNT(CASE WHEN NOT ub.IsSettled THEN 1 ELSE NULL END) AS UnsettledCount, 
            COALESCE(SUM(CASE WHEN NOT ub.IsSettled THEN e.Payment ELSE 0 END), 0) AS UnsettledPayment
        FROM Expenditures e
        LEFT JOIN UnsettledBridges ub ON e.BridgeID = ub.ID
        LEFT JOIN users u ON e.OpenID = u.openid
        GROUP BY u.name
        ORDER BY TotalPayment DESC
        `)
        if err != nil {
        log.Printf("查询支出记录失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{"error": "无法查询支出记录"})
        return
        }
        defer expenditureRows.Close()

        var expenditureStats []gin.H
        for expenditureRows.Next() {
        var name sql.NullString
        var totalPayment, totalCount, unsettledCount, unsettledPayment int
        if err := expenditureRows.Scan(&name, &totalPayment, &totalCount, &unsettledCount, &unsettledPayment); err != nil {
            log.Printf("扫描支出记录失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
            return
        }

        userName := name.String
        if !name.Valid {
            userName = "未知用户" // 默认值
        }

        // 查询用户头像
        var avatarUrl sql.NullString
        err := db.QueryRow(`
            SELECT bigHeadImgUrl
            FROM friends
            WHERE nickName = ? OR userName = ? OR remark = ?
            LIMIT 1
        `, userName, userName, userName).Scan(&avatarUrl)

        // 设置默认头像
        avatarUrlString := "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"

        // 如果查询成功且头像URL有效
        if err == nil && avatarUrl.Valid && avatarUrl.String != "" && strings.HasPrefix(avatarUrl.String, "http") {
            avatarUrlString = avatarUrl.String
        }

        expenditureStats = append(expenditureStats, gin.H{
            "UserName":         userName,
            "TotalPayment":     totalPayment,
            "TotalCount":       totalCount,       
            "UnsettledCount":   unsettledCount,  
            "UnsettledPayment": unsettledPayment,
            "AvatarUrl":        avatarUrlString,  // 添加头像URL
        })
        }

        // 新增: 查询梦乐的支付数据
        dreamLePaymentsRows, err := db2.Query(`
        SELECT 
            COALESCE(SUM(payment), 0) AS TotalDreamLePayment,
            COALESCE(SUM(CASE WHEN NOT is_check THEN payment ELSE 0 END), 0) AS UnsettledDreamLePayment,
            COUNT(*) AS TotalDreamLeCount,
            COUNT(CASE WHEN NOT is_check THEN 1 ELSE NULL END) AS UnsettledDreamLeCount
        FROM payments
        WHERE creditor = '国服车队联系员-梦乐'
        `)
        if err != nil {
        log.Printf("查询梦乐支付数据失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{"error": "无法查询梦乐支付数据"})
        return
        }
        defer dreamLePaymentsRows.Close()

        // 获取梦乐的支付数据
        var dreamLeTotalPayment, dreamLeUnsettledPayment, dreamLeTotalCount, dreamLeUnsettledCount int
        if dreamLePaymentsRows.Next() {
        if err := dreamLePaymentsRows.Scan(&dreamLeTotalPayment, &dreamLeUnsettledPayment, &dreamLeTotalCount, &dreamLeUnsettledCount); err != nil {
            log.Printf("扫描梦乐支付数据失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
            return
        }
        }

        // 查询梦乐的头像
        var dreamLeAvatarUrl sql.NullString
        err = db.QueryRow(`
        SELECT bigHeadImgUrl
        FROM friends
        WHERE nickName = ? OR userName = ? OR remark = ?
        LIMIT 1
        `, "国服车队联系员-梦乐", "国服车队联系员-梦乐", "国服车队联系员-梦乐").Scan(&dreamLeAvatarUrl)

        // 设置梦乐的头像URL
        dreamLeAvatarUrlString := "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
        if err == nil && dreamLeAvatarUrl.Valid && dreamLeAvatarUrl.String != "" && strings.HasPrefix(dreamLeAvatarUrl.String, "http") {
        dreamLeAvatarUrlString = dreamLeAvatarUrl.String
        }

        // 添加梦乐的数据到结果中
        expenditureStats = append(expenditureStats, gin.H{
        "UserName":         "国服车队联系员-梦乐",
        "TotalPayment":     dreamLeTotalPayment,
        "TotalCount":       dreamLeTotalCount,
        "UnsettledCount":   dreamLeUnsettledCount,
        "UnsettledPayment": dreamLeUnsettledPayment,
        "AvatarUrl":        dreamLeAvatarUrlString,  // 添加头像URL
        })

        // 按总支付金额重新排序
        sort.Slice(expenditureStats, func(i, j int) bool {
        return expenditureStats[i]["TotalPayment"].(int) > expenditureStats[j]["TotalPayment"].(int)
        })
            
        log.Printf("发单排行数据: %+v", expenditureStats)
        // 返回联系人、桥梁和发单排行数据
        c.JSON(http.StatusOK, gin.H{
            "friends":         friends,
            "bridges":         bridges,
            "expenditureStats": expenditureStats, // 发单支出排行
        })
    })
    r.POST("/get_unsettled_payments", func(c *gin.Context) {
        // 日志：接收到请求
        log.Printf("收到 /get_unsettled_payments 请求，方法: %s, 路径: %s", c.Request.Method, c.Request.URL.Path)
    
        // 解析请求数据
        var requestData struct {
            Creditor string `json:"creditor"`
        }
        if err := c.ShouldBindJSON(&requestData); err != nil {
            log.Printf("解析请求数据失败: %v, 请求体: %s", err, c.Request.Body)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
            return
        }
        creditor := requestData.Creditor
        log.Printf("解析请求成功，creditor: %s", creditor)
    
        // 直接从db2数据库中查询payments表
        log.Printf("开始查询payments表中的未结算数据，creditor: %s", creditor)
        rows, err := db2.Query(`
            SELECT 
                debtor, 
                SUM(payment) AS total_payment, 
                MIN(created_at) AS earliest_created_at
            FROM 
                payments
            WHERE 
                creditor = ? AND is_check = 0
            GROUP BY 
                debtor
        `, creditor)
        if err != nil {
            log.Printf("查询payments表失败: %v, creditor: %s", err, creditor)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取未结支付数据"})
            return
        }
        defer rows.Close()
    
        // 解析查询结果
        var unsettledPayments []gin.H
        rowCount := 0
        for rows.Next() {
            var debtor string
            var totalPayment int
            var earliestCreatedAt string
            if err := rows.Scan(&debtor, &totalPayment, &earliestCreatedAt); err != nil {
                log.Printf("扫描payments表结果失败: %v, creditor: %s, 行号: %d", err, creditor, rowCount+1)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据解析失败"})
                return
            }
            unsettledPayments = append(unsettledPayments, gin.H{
                "debtor":              debtor,
                "total_payment":       totalPayment,
                "earliest_created_at": earliestCreatedAt,
            })
            log.Printf("处理行数据成功，creditor: %s, debtor: %s, total_payment: %d, earliest_created_at: %s", 
                creditor, debtor, totalPayment, earliestCreatedAt)
            rowCount++
        }
    
        // 检查是否有查询错误
        if err := rows.Err(); err != nil {
            log.Printf("遍历payments表结果时发生错误: %v, creditor: %s", err, creditor)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据遍历失败"})
            return
        }
    
        log.Printf("完成payments表查询结果解析，creditor: %s, 共处理 %d 行数据", creditor, rowCount)
    
        // 返回JSON响应
        response := gin.H{
            "success": true,
            "data":    unsettledPayments,
        }
        log.Printf("准备返回响应，creditor: %s, 数据条数: %d", creditor, len(unsettledPayments))
        c.JSON(http.StatusOK, response)
    })
    r.POST("/place_order", func(c *gin.Context) {
        var orderData struct {
            InputContent string  `json:"inputContent"`
            BossId       string  `json:"bossId"`
            UserId       string  `json:"userId"` // 修改为字符串类型，接收前端传来的字符串
            Code         string  `json:"code"`
        }
        
        // 解析请求体
        if err := c.BindJSON(&orderData); err != nil {
            log.Printf("BindJSON 错误: %v, 数据: %+v", err, c.Request.Body)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
            return
        }
        log.Printf("接收到订单数据: %+v", orderData)
        
        // 使用 Code 获取 openid
        openid, err := getOpenIDFromCode(orderData.Code)
        if err != nil {
            log.Printf("获取 openid 出错: %v, Code: %s", err, orderData.Code)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取 openid"})
            return
        }
        log.Printf("成功获取 openid: %s", openid)
        
        var user struct {
            ID         int
            Username   string
            InviteCode *string // 保持为指针类型
        }
        err = db.QueryRow("SELECT id, username, invite_code FROM users WHERE openid = ?", openid).Scan(&user.ID, &user.Username, &user.InviteCode)
        if err != nil {
            log.Printf("查询用户数据出错: %v, openid: %s", err, openid)
            c.JSON(http.StatusForbidden, gin.H{"error": "用户数据查询失败，无法获取权限"})
            return
        }
        log.Printf("用户数据: %+v", user)
        
        if user.InviteCode == nil || *user.InviteCode != "000000" {
            log.Printf("用户 %s (%d) 无发单权限, InviteCode: %v", user.Username, user.ID, user.InviteCode)
            c.JSON(http.StatusForbidden, gin.H{"error": "没有权限", "redirect": "/scan_page"})
            return
        }
        
        log.Printf("用户 %s 拥有发单权限", user.Username)
        
        // 设置代发消息内容
        forwardMessage := orderData.InputContent + "，复制信息发我，这是代发"
        var contactUserName string
        
        if orderData.UserId != "" {
            // 查询friends表获取联系人userName
            err = db.QueryRow("SELECT userName FROM friends WHERE remark = ?", orderData.UserId).Scan(&contactUserName)
            if err != nil {
                log.Printf("查询friends表数据出错: %v, UserId: %s", err, orderData.UserId)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "联系人数据查询失败"})
                return
            }
            log.Printf("找到对应的联系人userName: %s", contactUserName)
            globalMessageContactMap[forwardMessage] = contactUserName
        } else {
            // 如果 UserId 为空，设置默认值
            contactUserName = "@@本人"
            log.Printf("UserId 为空，使用默认的联系人: %s", contactUserName)
        }
        
        // 将消息内容与游戏ID和联系人信息关联起来
        globalGameIDMap[forwardMessage] = orderData.BossId
        
        // 先不获取Bridge ID，保持原有逻辑
        createBridge(openid, "代发", contactUserName, forwardMessage, "来个车队", 0)
        forwardMessageToAllGroupswaibu(db, forwardMessage)
        
        // 使用findBridgeForContent获取刚创建的Bridge ID
        bridge, err := findBridgeForContent(forwardMessage)
        
        if err != nil {
            log.Printf("查询Bridge失败: %v", err)
            c.JSON(http.StatusOK, gin.H{"success": true, "message": "订单提交成功，但无法获取订单ID"})
            return
        }
        
        if bridge == nil {
            log.Printf("未找到刚创建的Bridge")
            c.JSON(http.StatusOK, gin.H{"success": true, "message": "订单提交成功，但未找到订单ID"})
            return
        }
        redirectURL := fmt.Sprintf("https://www.moki-flanke.icu/boss/%s", bridge.ID)
        // 返回Bridge ID
        c.JSON(http.StatusOK, gin.H{
            "success": true, 
            "message": "订单提交成功",
            "bridgeId": bridge.ID,
            "orderTime": time.Now().Format("2006-01-02 15:04:05"),
            "bossRoute": redirectURL,
        })
    })
    // 生成userOpenId的API
    r.POST("/create_user", func(c *gin.Context) {
        var req struct {
            Code     string `json:"code"`
            UserInfo struct {
                Nickname string `json:"nickname"`
                Avatar   string `json:"avatar"`
            } `json:"userInfo"`
        }
        
        // 绑定请求数据
        if err := c.ShouldBindJSON(&req); err != nil {
            log.Printf("绑定请求数据出错: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求数据格式错误"})
            return
        }
        log.Printf("收到创建用户请求，code: %s, nickname: %s", req.Code, req.UserInfo.Nickname)
        
        // 通过微信 code 获取 openid
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("获取 openid 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取 openid"})
            return
        }
        log.Printf("成功通过 code 获取 openid: %s", openid)
        
        // 查询用户是否已存在
        var exists bool
        err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE openid = ?)", openid).Scan(&exists)
        if err != nil {
            log.Printf("查询数据库出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询错误"})
            return
        }
        log.Printf("用户是否存在：%v", exists)
        
        if exists {
            // 如果用户已存在，查询并返回用户名
            var username string
            err = db.QueryRow("SELECT username FROM users WHERE openid = ?", openid).Scan(&username)
            if err != nil {
                log.Printf("查询用户名出错: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户信息失败"})
                return
            }
            log.Printf("用户已存在，返回用户名: %s", username)
            c.JSON(http.StatusOK, gin.H{
                "success": true,
                "message": "用户已存在",
                "username": username,
            })
            return
        }
        
        // 创建新用户
        username := generateRandomString(8)
        password := generateRandomString(12)
        log.Printf("生成的用户名: %s，密码: %s", username, password)
        
        _, err = db.Exec("INSERT INTO users (username, password, name, openid, Avatarpath) VALUES (?, ?, ?, ?, ?)",
            username, password, req.UserInfo.Nickname, openid, req.UserInfo.Avatar)
        if err != nil {
            log.Printf("插入新用户出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "创建用户失败"})
            return
        }
        log.Println("成功创建新用户")
        
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "message": "用户创建成功", 
            "username": username,
        })
    })
    r.GET("/api/players/list", func(c *gin.Context) {
        // 开始日志
        requestID := uuid.New().String()
        log.Printf("[%s] 开始处理 /api/players/list 请求", requestID)
        startTime := time.Now()
        
        // 获取 code 参数
        code := c.Query("code")
        var currentOpenID string
        
        // 如果提供了 code，获取对应的 openid
        if code != "" {
            openid, err := getOpenIDFromCode(code)
            if err != nil {
                log.Printf("[%s] 获取 OpenID 失败: %v", requestID, err)
                // 继续执行，但不使用特定用户的拉黑列表
            } else {
                currentOpenID = openid
            }
        }
        
        var userStats []map[string]interface{}
        
        // 数据库查询 - 根据当前用户的 openid 查询拉黑状态
        query := `
            SELECT 
                us.NickName, 
                us.GroupNickNames, 
                us.TotalStars, 
                us.BridgeCount, 
                us.CompleteOrderCount,
                us.IsReported,
                CASE 
                    WHEN ? != '' AND bl.id IS NOT NULL THEN 1 
                    ELSE 0 
                END as IsBlacklisted
            FROM user_stats us
            LEFT JOIN friends f ON us.NickName = f.nickName
            LEFT JOIN blacklist bl ON f.userName = bl.username 
                AND bl.is_active = 1 
                AND bl.openid = ?
            ORDER BY us.NickName
        `
        
        rows, err := db.Query(query, currentOpenID, currentOpenID)
        
        if err != nil {
            log.Printf("[%s] 数据库查询失败: %v", requestID, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户统计数据失败", "details": err.Error()})
            return
        }
        defer rows.Close()
        
        log.Printf("[%s] 数据库查询成功，处理结果集", requestID)
        rowCount := 0
        
        for rows.Next() {
            rowCount++
            var nickName, groupNickNames string
            var totalStars, bridgeCount, completeOrderCount int
            var isReported, isBlacklisted bool  // 修改为 bool 类型
            
            if err := rows.Scan(&nickName, &groupNickNames, &totalStars, &bridgeCount, &completeOrderCount, &isReported, &isBlacklisted); err != nil {
                log.Printf("[%s] 扫描行 #%d 时出错: %v", requestID, rowCount, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "处理用户数据失败", "details": err.Error()})
                return
            }
            // 处理群昵称，去重
            uniqueGroups := make(map[string]struct{})
            for _, groupName := range strings.Split(groupNickNames, ",") {
                trimmedName := strings.TrimSpace(groupName)
                if trimmedName != "" {
                    uniqueGroups[trimmedName] = struct{}{}
                }
            }
            
            var uniqueGroupNickNames []string
            for groupName := range uniqueGroups {
                uniqueGroupNickNames = append(uniqueGroupNickNames, groupName)
            }
            
            // 计算完成率
            completionRate := "N/A"
            if bridgeCount > 0 {
                completionRate = fmt.Sprintf("%.1f%%", float64(completeOrderCount)/float64(bridgeCount)*100)
            }
            
            // 查询用户的支出总和
            var totalPayment sql.NullInt64
            paymentErr := db.QueryRow("SELECT SUM(Payment) FROM Expenditures WHERE NickName = ?", nickName).Scan(&totalPayment)
            
            if paymentErr != nil {
                log.Printf("[%s] 查询用户 %s 支出时出错: %v", requestID, nickName, paymentErr)
                // 继续执行，不中断流程
            }
            
            totalPaymentStr := "0"
            if totalPayment.Valid {
                totalPaymentStr = fmt.Sprintf("%d", totalPayment.Int64)
            }
            
            userStats = append(userStats, map[string]interface{}{
                "NickName":           nickName,
                "GroupNickNames":     strings.Join(uniqueGroupNickNames, ", "),
                "TotalStars":         totalStars,
                "BridgeCount":        bridgeCount,
                "CompleteOrderCount": completeOrderCount,
                "CompletionRate":     completionRate,
                "TotalPayment":       totalPaymentStr,
                "IsReported":         isReported,      // 直接使用布尔值
                "IsBlacklisted":      isBlacklisted,   // 直接使用布尔值
            })
        }
        
        // 检查遍历过程中是否有错误
        if err = rows.Err(); err != nil {
            log.Printf("[%s] 遍历结果集时出错: %v", requestID, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "处理结果集失败", "details": err.Error()})
            return
        }
        
        // 生成响应
        log.Printf("[%s] 生成响应，数据条数: %d", requestID, len(userStats))
        
        response := gin.H{
            "success": true,
            "UserStats": userStats,
            "metadata": gin.H{
                "count": len(userStats),
                "requestID": requestID,
            },
        }
        
        // 返回JSON响应
        c.JSON(http.StatusOK, response)
        
        // 结束日志
        elapsedTime := time.Since(startTime)
        log.Printf("[%s] 完成请求处理，总耗时: %v", requestID, elapsedTime)
    })
    r.POST("/api/complaint", func(c *gin.Context) {
        var req struct {
            Creditor   string `json:"creditor"`
            Complaint  string `json:"complaint"`
        }
    
        // 绑定 JSON 请求体
        if err := c.BindJSON(&req); err != nil {
            log.Printf("Failed to bind JSON: %v", err)  // 记录错误日志
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
    
        // 检查指定昵称的用户是否存在
        userName, err := findUserNameByNickName("国1车队联系员-梦奇（24小时ai在）")
        if err != nil {
            log.Printf("User not found: %v", err)  // 记录用户未找到的日志
            c.JSON(http.StatusNotFound, gin.H{"error": "User not found", "redirectTo": "/scan_page1"})
            return
        }
    
        // 如果用户存在，发送消息
        message := "收到投诉用户：" + req.Creditor + "\n内容:" + req.Complaint
        sendTextMessage(message, userName)
    
        c.JSON(http.StatusOK, gin.H{"message": "投诉已提交"})
    })
    r.GET("/moban", func(c *gin.Context) {
        // 从 URL 查询参数中获取模板信息
        templateName := c.Query("template_name")
        orderDetails := c.Query("order_details")
        restrictedOrderDetails := c.Query("restricted_order_details")
        isCommonTemplate := false // 直接将其设为 false
        usageCount := 0 // 初始使用数量为 0
    
        // 打印接收到的参数
        fmt.Printf("接收到的模板信息: template_name=%s, order_details=%s, restricted_order_details=%s\n",
            templateName, orderDetails, restrictedOrderDetails)
    
        // 验证模板名是否为空
        if templateName == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "模板名称不能为空"})
            fmt.Println("模板名称为空，返回错误")
            return
        }
    
        // 将模板信息插入到数据库中的模板表
        query := `INSERT INTO Templates (TemplateName, OrderDetails, RestrictedOrderDetails, IsCommonTemplate, UsageCount)
                  VALUES (?, ?, ?, ?, ?)`
        
        result, err := db.Exec(query, templateName, orderDetails, restrictedOrderDetails, isCommonTemplate, usageCount)
        
        if err != nil {
            // 打印 SQL 执行的错误
            fmt.Printf("插入模板信息失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法存储模板信息: " + err.Error()})
            return
        }
    
        // 打印插入成功的结果
        rowsAffected, _ := result.RowsAffected()
        fmt.Printf("模板信息已成功存储, 受影响的行数: %d\n", rowsAffected)
    
        // 返回成功响应
        c.JSON(http.StatusOK, gin.H{"message": "模板信息已成功存储"})
    })    
    r.POST("/login_bot", func(c *gin.Context) {
        username := c.PostForm("username")
        password := c.PostForm("password")
    
        // 检查用户名和密码是否为空
        if username == "" || password == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名和密码不能为空"})
            return
        }
    
        // 查询用户信息，验证账号和密码
        var dbUsername, dbPassword string
        var isLoggedIn bool
        query := `SELECT username, password, is_logged_in FROM Users_bot WHERE username = ?`
        err := db.QueryRow(query, username).Scan(&dbUsername, &dbPassword, &isLoggedIn)
        if err != nil {
            log.Printf("查询用户信息时出错: %v", err)
            c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        // 检查密码是否正确
        if password != dbPassword {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        // 检查用户是否已经登录
        if isLoggedIn {
            c.JSON(http.StatusConflict, gin.H{"error": "该用户已登录"})
            return
        }
    
        // 更新用户登录状态为已登录
        updateQuery := `UPDATE Users_bot SET is_logged_in = TRUE WHERE username = ?`
        _, err = db.Exec(updateQuery, username)
        if err != nil {
            log.Printf("更新用户登录状态时出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法更新登录状态"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "登录成功", "redirect": "/dashboard"}) // 登录成功后跳转到dashboard页面
    })    
    r.POST("/register_bot", func(c *gin.Context) {
        username := c.PostForm("username")
        password := c.PostForm("password")
    
        // 检查用户名和密码是否为空
        if username == "" || password == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名和密码不能为空"})
            return
        }
    
        // 检查账号是否已存在
        var exists bool
        checkQuery := `SELECT EXISTS(SELECT 1 FROM Users_bot WHERE username = ?)`
        err := db.QueryRow(checkQuery, username).Scan(&exists)
        if err != nil {
            log.Printf("查询用户是否存在时出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法检查用户是否存在"})
            return
        }
    
        if exists {
            c.JSON(http.StatusConflict, gin.H{"error": "用户名已存在"})
            return
        }
    
        // 将用户信息插入到数据库
        insertQuery := `INSERT INTO Users_bot (username, password, balance, is_logged_in, remaining_days) 
                        VALUES (?, ?, 0.00, false, 0)`
        _, err = db.Exec(insertQuery, username, password)
        if err != nil {
            log.Printf("插入用户数据时出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法注册用户"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "注册成功"})
    })
    r.GET("/update_usage", func(c *gin.Context) {
        // 从查询参数中获取模板名称和新的使用次数
        templateName := c.Query("template_name")
        usageCountStr := c.Query("usage_count")
    
        // 验证参数是否为空
        if templateName == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "模板名称不能为空"})
            return
        }
    
        if usageCountStr == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "使用次数不能为空"})
            return
        }
    
        // 将使用次数从字符串转换为整数
        usageCount, err := strconv.Atoi(usageCountStr)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无效的使用次数"})
            return
        }
    
        // 打印接收到的参数
        log.Printf("接收到的使用次数更新请求: template_name=%s, usage_count=%d", templateName, usageCount)
    
        // 更新数据库中的使用次数
        query := `UPDATE Templates SET UsageCount = ? WHERE TemplateName = ?`
        result, err := db.Exec(query, usageCount, templateName)
        
        if err != nil {
            log.Printf("更新模板使用次数失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法更新使用次数: " + err.Error()})
            return
        }
    
        // 检查受影响的行数
        rowsAffected, _ := result.RowsAffected()
        if rowsAffected == 0 {
            log.Printf("未找到模板: %s", templateName)
            c.JSON(http.StatusNotFound, gin.H{"error": "未找到模板"})
            return
        }
    
        // 成功更新使用次数，返回成功消息
        log.Printf("模板使用次数已成功更新: %s, 新的使用次数: %d", templateName, usageCount)
        c.JSON(http.StatusOK, gin.H{"message": "模板使用次数已成功更新"})
    })
    
    r.POST("/api/payment", func(c *gin.Context) {
        var paymentData PaymentData
        if err := c.ShouldBindJSON(&paymentData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
            return
        }

        var existingID int
        err := db2.QueryRow("SELECT id FROM payments WHERE bridge_id = ? AND creditor = ?", paymentData.BridgeID, paymentData.Creditor).Scan(&existingID)

        if err == sql.ErrNoRows {
            // 插入新数据到 SQLite 数据库
            insertSQL := `INSERT INTO payments (bridge_id, payment, debtor, creditor, is_check, created_at) VALUES (?, ?, ?, ?, 0, ?)`
            statement, err := db2.Prepare(insertSQL)
            if err != nil {
                log.Fatal(err)
            }
            defer statement.Close()

            _, err = statement.Exec(paymentData.BridgeID, paymentData.Payment, paymentData.Debtor, paymentData.Creditor, time.Now())
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store data"})
                return
            }
        } else if err == nil {
            // 更新现有数据
            updateSQL := `UPDATE payments SET payment = ? WHERE bridge_id = ? AND creditor = ?`
            statement, err := db2.Prepare(updateSQL)
            if err != nil {
                log.Fatal(err)
            }
            defer statement.Close()

            _, err = statement.Exec(paymentData.Payment, paymentData.BridgeID, paymentData.Creditor)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update data"})
                return
            }
        } else {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Data processed successfully"})
    })
    // 新的GET路由，用于输出db2数据库中的RankPrices表数据
    r.GET("/api/rankprices", func(c *gin.Context) {
        rows, err := db2.Query("SELECT Rank, Price, StarCost, RankOrder FROM RankPrices")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        var rankPrices []struct {
            Rank      string `json:"rank"`
            Price     int    `json:"price"`
            StarCost  int    `json:"starCost"`
            RankOrder int    `json:"rankOrder"`
        }

        for rows.Next() {
            var rp struct {
                Rank      string `json:"rank"`
                Price     int    `json:"price"`
                StarCost  int    `json:"starCost"`
                RankOrder int    `json:"rankOrder"`
            }
            if err := rows.Scan(&rp.Rank, &rp.Price, &rp.StarCost, &rp.RankOrder); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            rankPrices = append(rankPrices, rp)
        }

        c.JSON(http.StatusOK, rankPrices)
    })
    r.GET("/api/playmate", func(c *gin.Context) {
        rows, err := db.Query("SELECT id, playmateID, imagePath, filePath, text, price FROM playmates")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()
    
        var playmates []struct {
            ID         string  `json:"id"`
            PlaymateID int     `json:"playmateID"`
            ImagePath  string  `json:"imagePath"`
            FilePath   string  `json:"filePath"`
            Text       string  `json:"text"`
            Price      float64 `json:"price"`
        }
    
        for rows.Next() {
            var playmate struct {
                ID         string  `json:"id"`
                PlaymateID int     `json:"playmateID"`
                ImagePath  string  `json:"imagePath"`
                FilePath   string  `json:"filePath"`
                Text       string  `json:"text"`
                Price      float64 `json:"price"`
            }
            if err := rows.Scan(&playmate.ID, &playmate.PlaymateID, &playmate.ImagePath, &playmate.FilePath, &playmate.Text, &playmate.Price); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            playmates = append(playmates, playmate)
        }
    
        c.JSON(http.StatusOK, playmates)
    })
    
    // 定义一个 POST 路由
    r.POST("/api/rm", func(c *gin.Context) {
        var data PaymentData

        // 解析 JSON 请求体
        if err := c.ShouldBindJSON(&data); err != nil {
            log.Printf("Error binding JSON: %v\n", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        log.Printf("Received data: %+v\n", data)

        // 更新数据库中的记录
        result, err := db2.Exec("UPDATE payments SET is_check = 1 WHERE bridge_id = ?", data.BridgeID)
        if err != nil {
            log.Printf("Error updating database: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Database update failed"})
            return
        }

        rowsAffected, err := result.RowsAffected()
        if err != nil {
            log.Printf("Error getting rows affected: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve rows affected"})
            return
        }

        log.Printf("Database update successful, %d rows affected\n", rowsAffected)

        // 返回成功响应
        c.JSON(http.StatusOK, gin.H{"message": "请求已成功接收并处理"})
    })

    // 定义 GET 路由以获取所有债务数据
    r.GET("/api/debts", func(c *gin.Context) {
        rows, err := db2.Query("SELECT bridge_id, payment, debtor, creditor, is_check, created_at FROM payments")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database"})
            return
        }
        defer rows.Close()
        var debts []struct {
            BridgeID  string `json:"bridge_id"`
            Payment   int    `json:"payment"`
            Debtor    string `json:"debtor"`
            Creditor  string `json:"creditor"`
            IsCheck   bool   `json:"is_check"`
            CreatedAt string `json:"created_at"`
        }
        for rows.Next() {
            var debt struct {
                BridgeID  string `json:"bridge_id"`
                Payment   int    `json:"payment"`
                Debtor    string `json:"debtor"`
                Creditor  string `json:"creditor"`
                IsCheck   bool   `json:"is_check"`
                CreatedAt string `json:"created_at"`
            }
            err := rows.Scan(&debt.BridgeID, &debt.Payment, &debt.Debtor, &debt.Creditor, &debt.IsCheck, &debt.CreatedAt)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan data"})
                return
            }
            debts = append(debts, debt)
        }

        c.JSON(http.StatusOK, debts)
    })
   // 绑定API - 根据微信code获取openid并生成绑定码
    r.POST("/api/binding/register", func(c *gin.Context) {
        log.Printf("接收到绑定请求，开始处理...")
        
        var req struct {
            Code string `json:"code"`
        }
        
        // 读取原始请求体并记录
        body, err := c.GetRawData()
        if err != nil {
            log.Printf("读取请求体失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "读取请求体失败"})
            return
        }
        
        log.Printf("接收到的原始请求体: %s", string(body))
        
        // 重新设置请求体
        c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
        
        // 绑定JSON请求体
        if err := c.BindJSON(&req); err != nil {
            log.Printf("Failed to bind JSON: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        
        log.Printf("解析后的请求参数: Code=%s", req.Code)
        
        // 验证code是否为空
        if req.Code == "" {
            log.Printf("微信登录凭证为空")
            c.JSON(http.StatusBadRequest, gin.H{"error": "微信登录凭证不能为空"})
            return
        }
        
        // 获取OpenID
        log.Printf("开始获取OpenID...")
        openID, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取OpenID失败"})
            return
        }
        log.Printf("成功获取OpenID: %s", openID)
        
        // 生成8位随机数字作为绑定码
        bindCode := generateBindCode()
        log.Printf("生成的绑定码: %s", bindCode)
        
        // 将绑定码保存到数据库，并关联OpenID
        log.Printf("开始保存绑定码到数据库...")
        if err := saveBindCode(openID, bindCode); err != nil {
            log.Printf("保存绑定码失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "生成绑定码失败"})
            return
        }
        log.Printf("绑定码保存成功")
        
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "bindCode": bindCode,
        })
        log.Printf("绑定请求处理完成，返回绑定码: %s", bindCode)
    })

    // 查询绑定状态API
    r.GET("/api/binding/status/:code", func(c *gin.Context) {
        // 获取绑定码
        bindCode := c.Param("code")
        log.Printf("接收到查询绑定状态请求，绑定码: %s", bindCode)
        
        // 检查绑定码是否有效
        log.Printf("开始检查绑定码状态...")
        openID, used, err := checkBindCode(bindCode)
        if err != nil {
            log.Printf("检查绑定码失败: %v", err)
            c.JSON(http.StatusNotFound, gin.H{"error": "无效的绑定码"})
            return
        }
        
        if used {
            log.Printf("绑定码 %s 已被使用，关联的OpenID: %s", bindCode, openID)
        } else {
            log.Printf("绑定码 %s 未被使用，关联的OpenID: %s", bindCode, openID)
        }
        
        if !used {
            // 绑定码未使用
            c.JSON(http.StatusOK, gin.H{
                "status": "pending",
            })
            log.Printf("返回状态: pending")
            return
        }
        
        // 绑定码已使用，获取用户信息
        log.Printf("开始获取用户信息...")
        userInfo, err := getUserInfoByOpenID(openID)
        if err != nil {
            log.Printf("获取用户信息失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
            return
        }
        
        log.Printf("成功获取用户信息: %+v", userInfo)
        
        c.JSON(http.StatusOK, gin.H{
            "status": "bound",
            "userInfo": userInfo,
        })
        log.Printf("返回状态: bound，包含用户信息")
    })
    // 获取用户订单历史记录
    r.POST("/api/orders/history", func(c *gin.Context) {
        log.Printf("接收到获取订单历史请求，开始处理...")
        
        // 解析请求体获取Code
        var req struct {
            Code string `json:"code"`
        }
        
        // 读取原始请求体并记录
        body, err := c.GetRawData()
        if err != nil {
            log.Printf("读取请求体失败: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "读取请求体失败"})
            return
        }
        
        log.Printf("接收到的原始请求体: %s", string(body))
        
        // 重新设置请求体
        c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
        
        // 绑定JSON请求体
        if err := c.BindJSON(&req); err != nil {
            log.Printf("Failed to bind JSON: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        
        log.Printf("解析后的请求参数: Code=%s", req.Code)
        
        // 验证code是否为空
        if req.Code == "" {
            log.Printf("微信登录凭证为空")
            c.JSON(http.StatusBadRequest, gin.H{"error": "微信登录凭证不能为空"})
            return
        }
        
        // 获取OpenID
        log.Printf("开始获取OpenID...")
        openID, err := getOpenIDFromCode(req.Code)
        if err != nil {
            log.Printf("获取OpenID失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取OpenID失败"})
            return
        }
        log.Printf("成功获取OpenID: %s", openID)
        
        
        // 根据openid直接查询wechatname
        var wechatname string
        err = db.QueryRow("SELECT wechatname FROM users WHERE openid = ?", openID).Scan(&wechatname)
        if err != nil {
            log.Printf("查询用户信息失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
            return
        }
        
        // 查询nickname
        var nickname string
        err = db.QueryRow("SELECT nickName FROM friends WHERE userName = ?", wechatname).Scan(&nickname)
        if err != nil {
            log.Printf("查询好友昵称失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取好友信息失败"})
            return
        }
        
        // 查询订单
        rows, err := db.Query(`
            SELECT ID, IsActive, Msg, GameID, Stars, CreatedAt
            FROM Bridges 
            WHERE WeChatUser = ?
        `, nickname)
        if err != nil {
            log.Printf("查询订单记录失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单记录失败"})
            return
        }
        defer rows.Close()
        
        var orders []gin.H
        for rows.Next() {
            var id, msg, gameID string
            var stars int
            var createdAt time.Time
            var isActive bool
            
            err := rows.Scan(&id, &isActive, &msg, &gameID, &stars, &createdAt)
            if err != nil {
                log.Printf("读取订单数据失败: %v", err)
                continue
            }
            
            var orderStatus string
            var price int
            
            // 修改逻辑：当星数为负数或为0时，首先判断是炸单
            if stars <= 0 {
                orderStatus = "exploded"
            } else {
                // 其他情况根据gameID来判断
                if gameID == "" {
                    // 如果gameID为空，并且isActive为true，就是代练中状态
                    if isActive {
                        orderStatus = "playing"
                    } else {
                        // gameID为空但isActive为false，视为炸单
                        orderStatus = "exploded"
                    }
                } else {
                    // gameID存在，查询是否已结账 (不再依赖isActive)
                    var isSettled sql.NullBool
                    err := db.QueryRow("SELECT IsSettled FROM UnsettledBridges WHERE ID = ?", id).Scan(&isSettled)
                    
                    if err != nil || !isSettled.Valid {
                        orderStatus = "exploded" // 查询失败或无结账记录视为炸单
                    } else {
                        if isSettled.Bool {
                            orderStatus = "paid" // 已结账
                        } else {
                            orderStatus = "unpaid" // 未结账
                        }
                    }
                }
            }
            
            // 查询金额 (对任何状态都尝试查询金额)
            var payment sql.NullInt64
            err = db.QueryRow("SELECT Payment FROM Expenditures WHERE BridgeID = ?", id).Scan(&payment)
            if err == nil && payment.Valid {
                price = int(payment.Int64)
            }
            
            orders = append(orders, gin.H{
                "orderId":     id,
                "orderTime":   createdAt,
                "orderStatus": orderStatus,
                "bossName":    gameID,
                "bossStars":   stars,
                "price":       price,
                "message":     msg,
            })
        }
        
        log.Printf("成功获取 %d 条订单记录", len(orders))
        c.JSON(http.StatusOK, orders)
    })
    r.GET("/scan_page", func(c *gin.Context) {
        c.HTML(http.StatusOK, "scan.html", nil) // 显示扫码页面
    })

    // 定义 GET 路由以获取所有公告数据
    r.GET("/api/gonggao", func(c *gin.Context) {
        rows, err := db2.Query("SELECT id, message, created_at FROM announcements")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database"})
            return
        }
        defer rows.Close()

        var announcements []Announcement
        for rows.Next() {
            var announcement Announcement
            err := rows.Scan(&announcement.ID, &announcement.Message, &announcement.CreatedAt)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan data"})
                return
            }
            announcements = append(announcements, announcement)
        }

        c.JSON(http.StatusOK, announcements)
    })
    // 登录页面
    r.GET("/login", func(c *gin.Context) {
        c.HTML(http.StatusOK, "login.html", nil)
    })
    // 登录页面
    r.GET("/seller", func(c *gin.Context) {
        c.HTML(http.StatusOK, "seller.html", nil)
    })

    r.POST("/login", func(c *gin.Context) {
        var loginInfo struct {
            Username string `form:"username"`
            Password string `form:"password"`
        }
        if err := c.ShouldBind(&loginInfo); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "表单信息不完整"})
            return
        }
    
        // 查询数据库以获取用户详细信息，包括邀请码和被使用的邀请码
        var hashedPassword, aiGroup, starJournal, name, inviteCode, usedInviteCode string
        err := db.QueryRow("SELECT password, ai_group, star_journal, name, invite_code, used_invite_code FROM users WHERE username = ?", loginInfo.Username).Scan(&hashedPassword, &aiGroup, &starJournal, &name, &inviteCode, &usedInviteCode)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        // 检查加密的密码是否与数据库中的密码匹配
        if err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(loginInfo.Password)); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        session := sessions.Default(c)
        session.Set("user", loginInfo.Username)
        session.Set("name", name)
        session.Set("userIP", c.ClientIP())
        session.Set("ai_group", aiGroup)
        session.Set("invite_code", inviteCode)       // 设置用户的邀请码
        session.Set("used_invite_code", usedInviteCode) // 设置用户注册时使用的邀请码
    
        if aiGroup == "" {
            session.Set("stars_count", starJournal)
        } else {
            var starsCount int
            err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE UserName = ? AND GroupID = ?", name, aiGroup).Scan(&starsCount)
            if err != nil && err != sql.ErrNoRows {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询星星数失败"})
                return
            }
            session.Set("stars_count", starsCount)
        }
    
        session.Save()
    
        // 返回登录成功信息和重定向URL
        c.JSON(http.StatusOK, gin.H{"message": "登录成功", "redirect": "/"})
    })    
    
    r.GET("/scan_page1", func(c *gin.Context) {
        c.HTML(http.StatusOK, "scan.html", nil) // 显示扫码页面
    })
    r.GET("/suno", func(c *gin.Context) {
        c.HTML(http.StatusOK, "suno.html", nil) // 显示扫码页面
    })
    // 注册页面
    r.GET("/register", func(c *gin.Context) {
        c.HTML(http.StatusOK, "register.html", nil)
    })
    r.GET("/register/:inviteCode", func(c *gin.Context) {
        inviteCode := c.Param("inviteCode")
        
        // 检查inviteCode是否为六位数字
        match, _ := regexp.MatchString("^\\d{6}$", inviteCode)
        if !match {
            c.HTML(http.StatusBadRequest, "error.html", gin.H{"error": "邀请码无效"})
            return
        }
        
        // 打印日志信息
        log.Printf("Received request for /register with inviteCode: %s", inviteCode)
        
        c.HTML(http.StatusOK, "register.html", gin.H{
            "InviteCode": inviteCode,
        })
    })    
    // 登录页面
    r.GET("/hero", func(c *gin.Context) {
        c.HTML(http.StatusOK, "li.html", nil)
    })
    r.GET("/hero_zhanli", func(c *gin.Context) {
        c.HTML(http.StatusOK, "zhan.html", nil)
    })
    
    r.POST("/register", func(c *gin.Context) {
        var newUser struct {
            Username   string `form:"username" binding:"required"`
            Password   string `form:"password" binding:"required"`
            Name       string `form:"name" binding:"required"`
            AiGroup    string `form:"ai_group"`    // 可以为空
            InviteCode string `form:"inviteCode"`  // 新增邀请码字段
        }
        if err := c.ShouldBind(&newUser); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "表单信息不完整"})
            return
        }
    
        // 验证用户名是否只包含英文字符和数字
        match, _ := regexp.MatchString("^[a-zA-Z0-9]+$", newUser.Username)
        if !match {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名只能包含英文字符和数字"})
            return
        }
    
        // 密码加密
        hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newUser.Password), bcrypt.DefaultCost)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"})
            return
        }
    
        // 检查username是否已存在
        var userExists int
        err = db.QueryRow("SELECT COUNT(*) FROM users WHERE username = ?", newUser.Username).Scan(&userExists)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法验证用户名"})
            return
        }
    
        if userExists > 0 {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在，请选择其他用户名"})
            return
        }
    
        // 检查数据库中是否已经存在具有相同名字和AI群的用户
        var nameGroupExists int
        err = db.QueryRow("SELECT COUNT(*) FROM users WHERE name = ? AND ai_group = ?", newUser.Name, newUser.AiGroup).Scan(&nameGroupExists)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法验证用户信息"})
            return
        }
    
        if nameGroupExists > 0 {
            c.JSON(http.StatusBadRequest, gin.H{"error": "该名字已经被绑定，请更换名字"})
            return
        }
    
        // 生成唯一的邀请码
        userInviteCode := generateUniqueInviteCode()
    
        // 插入新用户，包括使用的邀请码和自己的邀请码
        _, err = db.Exec("INSERT INTO users (username, password, name, ai_group, invite_code, used_invite_code, star_journal) VALUES (?, ?, ?, ?, ?, ?, 0)",
            newUser.Username, hashedPassword, newUser.Name, newUser.AiGroup, userInviteCode, newUser.InviteCode)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "用户创建失败"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "注册成功，请登录"})
    })    
// 微信小程序登录处理路由
r.GET("/", func(c *gin.Context) {
    // 检查是否有微信登录凭证
    code := c.Query("code")
    
    // 如果没有code，说明不是从微信小程序访问，重定向到登录页面
    if code == "" {
        c.Redirect(http.StatusSeeOther, "/login")
        return
    }
    
    // 有code，进行微信登录处理
    log.Printf("接收到微信登录凭证: Code=%s", code)
    
    // 获取OpenID
    openid, err := getOpenIDFromCode(code)
    if err != nil {
        log.Printf("[ERROR] 获取 OpenID 失败: %v", err)
        c.HTML(http.StatusInternalServerError, "error.html", gin.H{
            "error": "获取用户信息失败",
        })
        return
    }
    
    // 查询是否存在用户
    var userExists int
    var existingUser struct {
        ID            int
        Username      string
        Name          string
        AiGroup       string
        StarJournal   int
        InviteCode    string
        UsedInviteCode sql.NullString
    }
    
    err = db.QueryRow(`
        SELECT COUNT(*), id, username, IFNULL(name, ''), IFNULL(ai_group, ''), 
        star_journal, invite_code, used_invite_code 
        FROM users WHERE openid = ? LIMIT 1`, openid).Scan(
        &userExists, 
        &existingUser.ID, 
        &existingUser.Username, 
        &existingUser.Name, 
        &existingUser.AiGroup, 
        &existingUser.StarJournal, 
        &existingUser.InviteCode, 
        &existingUser.UsedInviteCode,
    )
    
    if err != nil && err != sql.ErrNoRows {
        log.Printf("查询用户数据库失败: %v", err)
        c.HTML(http.StatusInternalServerError, "error.html", gin.H{
            "error": "查询用户数据库失败",
        })
        return
    }
    
    session := sessions.Default(c)
    var newUserPassword string
    var isNewUser bool
    
    // 如果用户存在，就使用现有用户信息
    if userExists > 0 {
        session.Set("user", existingUser.Username)
        session.Set("user_id", existingUser.ID)
        session.Set("name", existingUser.Name)
        session.Set("ai_group", existingUser.AiGroup)
        session.Set("stars_count", existingUser.StarJournal)
        session.Set("invite_code", existingUser.InviteCode)
        
        if existingUser.UsedInviteCode.Valid {
            session.Set("used_invite_code", existingUser.UsedInviteCode.String)
        } else {
            session.Set("used_invite_code", "")
        }
        
        isNewUser = false
    } else {
        // 用户不存在，创建新用户
        randomUsername := fmt.Sprintf("wx_%s", generateRandomString(8))
        newUserPassword = generateRandomString(12)
        
        // 密码加密
        hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newUserPassword), bcrypt.DefaultCost)
        if err != nil {
            log.Printf("密码加密失败: %v", err)
            c.HTML(http.StatusInternalServerError, "error.html", gin.H{
                "error": "创建账号失败",
            })
            return
        }
        
        // 生成唯一的邀请码
        userInviteCode := generateUniqueInviteCode()
        
        // 创建新用户 - 这里name与username相同
        result, err := db.Exec(`
            INSERT INTO users (username, password, name, ai_group, invite_code, openid, star_journal, balance) 
            VALUES (?, ?, ?, '', ?, ?, 0, 0.0)`,
            randomUsername, hashedPassword, randomUsername, userInviteCode, openid)
        
        if err != nil {
            log.Printf("创建新用户失败: %v", err)
            c.HTML(http.StatusInternalServerError, "error.html", gin.H{
                "error": "创建新用户失败",
            })
            return
        }
        
        newUserId, err := result.LastInsertId()
        if err != nil {
            log.Printf("获取新用户ID失败: %v", err)
        }
        
        // 设置会话
        session.Set("user", randomUsername)
        session.Set("user_id", newUserId)
        session.Set("name", randomUsername)
        session.Set("ai_group", "")
        session.Set("stars_count", 0)
        session.Set("invite_code", userInviteCode)
        session.Set("used_invite_code", "")
        
        isNewUser = true
    }
    
    // 保存IP地址到会话
    session.Set("userIP", c.ClientIP())
    
    if err := session.Save(); err != nil {
        log.Printf("保存会话失败: %v", err)
        c.HTML(http.StatusInternalServerError, "error.html", gin.H{
            "error": "保存会话失败",
        })
        return
    }
    
    // 获取会话中的用户信息
    username := session.Get("user")
    name := session.Get("name")
    aiGroup := session.Get("ai_group")
    starsCount := 0
    
    // 查询星星数量
    if aiGroup == "" {
        var starJournal int
        err := db.QueryRow("SELECT star_journal FROM users WHERE username = ?", username).Scan(&starJournal)
        if err != nil && err != sql.ErrNoRows {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询星星数失败"})
            return
        }
        starsCount = starJournal
    } else {
        err := db.QueryRow("SELECT StarsCount FROM member_stars WHERE UserName = ? AND GroupID = ?", name, aiGroup).Scan(&starsCount)
        if err != nil && err != sql.ErrNoRows {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询星星数失败"})
            return
        }
    }
    
    // 更新会话中的星星数
    session.Set("stars_count", starsCount)
    if err := session.Save(); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "无法保存会话"})
        return
    }     
    inviteCode := session.Get("invite_code")
    usedInviteCode := session.Get("used_invite_code")
    var allOrders []ExtendedOrder
    var totalFrozenStarCost int

    // 确保每个Scan函数调用中的参数列表格式正确，每行末尾都有逗号
    queryWeb := `SELECT b.ID, b.GroupID, b.GroupName, b.GroupUserNickName, b.WeChatUser, b.IsActive, b.IsCompleted, b.Msg, b.GameID, IFNULL(NULLIF(b.Stars, ''), 0), IFNULL(NULLIF(b.StarCost, ''), 0), b.OrderType, b.CreatedAt, b.LastMessageTime, b.FinalRank, b.WeChatUsername FROM Bridges b JOIN WebOrders w ON b.ID = w.ID WHERE b.GroupUserNickName = ?`
    rowsWeb, err := db.Query(queryWeb, username)
    if err != nil {
        fmt.Printf("Error fetching web orders: %v\n", err)
    } else {
        defer rowsWeb.Close()
        for rowsWeb.Next() {
            var order Order
            var lastMessageTimeStr string
            if err := rowsWeb.Scan(
                &order.ID, 
                &order.GroupID, 
                &order.GroupName, 
                &order.GroupUserNickName, 
                &order.WeChatUser, 
                &order.IsActive, 
                &order.IsCompleted, 
                &order.Msg, 
                &order.GameID, 
                &order.Stars, 
                &order.StarCost, 
                &order.OrderType, 
                &order.CreatedAt, 
                &lastMessageTimeStr, 
                &order.FinalRank, 
                &order.WeChatUsername,
            ); err != nil {
                fmt.Printf("Error scanning web order: %v\n", err)
            } else {
                if order.LastMessageTime, err = time.Parse(time.RFC3339Nano, lastMessageTimeStr); err != nil {
                    fmt.Printf("Error parsing LastMessageTime: %v\n", err)
                    order.LastMessageTime = time.Time{}
                }

                ranksCosts, err := getAllRanksAndCosts(db)
                if err != nil {
                    return
                }

                matchedPeak, _ := parsePeakRank(order.Msg)
                var matchedRanks []string

                if matchedPeak != "" {
                    matchedRanks = append(matchedRanks, matchedPeak)
                } else {
                    sort.Slice(ranksCosts, func(i, j int) bool {
                        return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                    })
                    var ranks []string
                    for _, rankCost := range ranksCosts {
                        ranks = append(ranks, rankCost[0])
                    }
                    for _, rank := range ranks {
                        rankOccurrences := strings.Count(order.Msg, rank)
                        for i := 0; i < rankOccurrences; i++ {
                            matchedRanks = append(matchedRanks, rank)
                            order.Msg = strings.Replace(order.Msg, rank, "", 1)
                        }
                    }
                }
                order.Msg = strings.Join(matchedRanks, " + ")

                frozenStarCost, err := getTotalFrozenStarCost(db, order.ID)
                if err != nil {
                    fmt.Printf("Error fetching frozen StarCost: %v\n", err)
                } else {
                    totalFrozenStarCost += frozenStarCost
                }

                allOrders = append(allOrders, ExtendedOrder{Order: order, Source: "网站"})
            }
        }
    }

    // 修复AI群订单查询
    if aiGroup != "未加入任何群组" {
        queryAI := `SELECT ID, GroupID, GroupName, GroupUserNickName, WeChatUser, IsActive, IsCompleted, Msg, GameID, IFNULL(NULLIF(Stars, ''), 0), IFNULL(NULLIF(StarCost, ''), 0), OrderType, CreatedAt, LastMessageTime, FinalRank, WeChatUsername FROM Bridges WHERE GroupUserNickName = ? AND GroupName = ?`
        rowsAI, err := db.Query(queryAI, name, aiGroup)
        if err != nil {
            fmt.Printf("Error fetching AI group orders: %v\n", err)
        } else {
            defer rowsAI.Close()
            for rowsAI.Next() {
                var order Order
                var lastMessageTimeStr string
                if err := rowsAI.Scan(
                    &order.ID, 
                    &order.GroupID, 
                    &order.GroupName, 
                    &order.GroupUserNickName, 
                    &order.WeChatUser, 
                    &order.IsActive, 
                    &order.IsCompleted, 
                    &order.Msg, 
                    &order.GameID, 
                    &order.Stars, 
                    &order.StarCost, 
                    &order.OrderType, 
                    &order.CreatedAt, 
                    &lastMessageTimeStr, 
                    &order.FinalRank, 
                    &order.WeChatUsername,
                ); err != nil {
                    fmt.Printf("Error scanning AI group order: %v\n", err)
                } else {
                    if order.LastMessageTime, err = time.Parse(time.RFC3339Nano, lastMessageTimeStr); err != nil {
                        fmt.Printf("Error parsing LastMessageTime: %v\n", err)
                        order.LastMessageTime = time.Time{}
                    }

                    ranksCosts, err := getAllRanksAndCosts(db)
                    if err != nil {
                        return
                    }

                    matchedPeak, _ := parsePeakRank(order.Msg)
                    var matchedRanks []string

                    if matchedPeak != "" {
                        matchedRanks = append(matchedRanks, matchedPeak)
                    } else {
                        sort.Slice(ranksCosts, func(i, j int) bool {
                            return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                        })
                        var ranks []string
                        for _, rankCost := range ranksCosts {
                            ranks = append(ranks, rankCost[0])
                        }
                        for _, rank := range ranks {
                            rankOccurrences := strings.Count(order.Msg, rank)
                            for i := 0; i < rankOccurrences; i++ {
                                matchedRanks = append(matchedRanks, rank)
                                order.Msg = strings.Replace(order.Msg, rank, "", 1)
                            }
                        }
                    }
                    order.Msg = strings.Join(matchedRanks, " + ")
                    allOrders = append(allOrders, ExtendedOrder{Order: order, Source: "AI群"})
                }
            }
        }
    }

    playmateQuery := `SELECT ID, playmateID, imagePath, filePath, text, price FROM playmates`
    rowsPlaymates, err := db.Query(playmateQuery)
    if err != nil {
        fmt.Printf("Error fetching playmates: %v\n", err)
    }

    var playmates []Playmate
    if rowsPlaymates != nil {
        defer rowsPlaymates.Close()
        for rowsPlaymates.Next() {
            var playmate Playmate
            var id, imagePath, filePath, text sql.NullString
            var price sql.NullInt64
            if err := rowsPlaymates.Scan(&id, &playmate.PlaymateID, &imagePath, &filePath, &text, &price); err != nil {
                fmt.Printf("Error scanning playmate: %v\n", err)
            } else {
                playmate.ID = handleNullString(id)
                playmate.ImagePath = handleNullString(imagePath)
                playmate.FilePath = handleNullString(filePath)
                playmate.Text = handleNullString(text)
                playmate.Price = int(handleNullInt64(price))
                playmates = append(playmates, playmate)
            }
        }
    }

    tradeItemsQuery := `SELECT id, IFNULL(seller, 'default_seller'), IFNULL(buyers, 'default_buyers'), IFNULL(item_name, 'default_item_name'), IFNULL(description, 'default_description'), IFNULL(price, 0), IFNULL(quantity, 1), IFNULL(image_file_name, 'default_image_path') FROM trade_items`
    rowsTradeItems, err := db.Query(tradeItemsQuery)
    if err != nil {
        fmt.Printf("Error fetching trade items: %v\n", err)
    }
    var tradeItems []TradeItem
    if rowsTradeItems != nil {
        defer rowsTradeItems.Close()
        for rowsTradeItems.Next() {
            var tradeItem TradeItem
            if err := rowsTradeItems.Scan(&tradeItem.ID, &tradeItem.Seller, &tradeItem.Buyers, &tradeItem.ItemName, &tradeItem.Description, &tradeItem.Price, &tradeItem.Quantity, &tradeItem.ImageFileName); err != nil {
                fmt.Printf("Error scanning trade item: %v\n", err)
            } else {
                if tradeItem.ImageFileName != "default_image_path" {
                    tradeItem.ImageFileName = "./jiaoyi/" + tradeItem.ImageFileName
                    tradeItems = append(tradeItems, tradeItem)
                }
            }
        }
    }

    userTradeItemsQuery := `SELECT id, IFNULL(seller, 'default_seller'), IFNULL(buyers, 'default_buyers'), IFNULL(item_name, 'default_item_name'), IFNULL(description, 'default_description'), IFNULL(price, 0), IFNULL(quantity, 1), IFNULL(image_file_name, 'default_image_path') FROM trade_items WHERE seller = ?`
    userRows, err := db.Query(userTradeItemsQuery, name)
    if err != nil {
        fmt.Printf("Error fetching user trade items: %v\n", err)
        return
    }
    defer userRows.Close()
    var userTradeItems []TradeItem
    for userRows.Next() {
        var item TradeItem
        if err := userRows.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
            fmt.Printf("Error scanning user trade item: %v\n", err)
            continue
        }
        userTradeItems = append(userTradeItems, item)
    }

    var contactingOrders []ExtendedOrder
    var ongoingOrders []ExtendedOrder
    var completedOrders []ExtendedOrder
    
    for _, order := range allOrders {
        if order.IsActive && order.WeChatUser == "" {
            contactingOrders = append(contactingOrders, order)
        } else if order.IsActive && order.WeChatUser != "" {
            ongoingOrders = append(ongoingOrders, order)
        } else if !order.IsActive && order.WeChatUser != "" {
            completedOrders = append(completedOrders, order)
        }
    }
    
    // Adjust CreatedAt for contactingOrders
    for i := range contactingOrders {
        contactingOrders[i].CreatedAt = contactingOrders[i].CreatedAt.Add(8 * time.Hour)
    }
    
    // Adjust CreatedAt for ongoingOrders
    for i := range ongoingOrders {
        ongoingOrders[i].CreatedAt = ongoingOrders[i].CreatedAt.Add(8 * time.Hour)
    }
    
    // Adjust CreatedAt for completedOrders
    for i := range completedOrders {
        completedOrders[i].CreatedAt = completedOrders[i].CreatedAt.Add(8 * time.Hour)
    }
    
    sort.Slice(contactingOrders, func(i, j int) bool {
        return contactingOrders[i].CreatedAt.After(contactingOrders[j].CreatedAt)
    })
    sort.Slice(ongoingOrders, func(i, j int) bool {
        return ongoingOrders[i].CreatedAt.After(ongoingOrders[j].CreatedAt)
    })
    sort.Slice(completedOrders, func(i, j int) bool {
        return completedOrders[i].CreatedAt.After(completedOrders[j].CreatedAt)
    })
    
    var eventText string
    err = db.QueryRow("SELECT event_text FROM current_event WHERE id = 1").Scan(&eventText)
    if err != nil && err != sql.ErrNoRows {
        fmt.Printf("Error fetching event text: %v\n", err)
        eventText = "No current event"
    }
    eventText = strings.ReplaceAll(eventText, "\n", "<br>")

    re := regexp.MustCompile(`(\d+)(星卷|一星)`)
    replacedText := re.ReplaceAllStringFunc(eventText, func(s string) string {
        match := re.FindStringSubmatch(s)
        if num, err := strconv.Atoi(match[1]); err == nil {
            if match[2] == "星卷" || match[2] == "一星" {
                newNum := float64(num) / 2
                if newNum == float64(int(newNum)) {
                    return fmt.Sprintf("%.0f%s", newNum, match[2])
                } else {
                    return fmt.Sprintf("%.1f%s", newNum, match[2])
                }
            }
        }
        return s
    })

    replacedText = strings.ReplaceAll(replacedText, "\n", "<br>")

    rankQuery := "SELECT Rank, Price, StarCost, RankOrder FROM RankPrices WHERE RankOrder BETWEEN 333 AND 498 OR RankOrder >= 499"
    rankRows, err := db.Query(rankQuery)
    if err != nil && err != sql.ErrNoRows {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve rank prices"})
        return
    }
    defer rankRows.Close()

    var ranks []map[string]interface{}
    for rankRows.Next() {
        var rank string
        var price, starCost, rankOrder int
        if err := rankRows.Scan(&rank, &price, &starCost, &rankOrder); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan rank prices"})
            return
        }

        encryptedPrice := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%d", price)))

        ranks = append(ranks, map[string]interface{}{
            "Rank":      rank,
            "Price":     encryptedPrice,
            "StarCost":  starCost,
            "RankOrder": rankOrder,
        })
    }
    ranksJSON, err := json.Marshal(ranks)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize ranks"})
        return
    }

    usedInviteCodesQuery := "SELECT Username, Amount FROM UserRechargeLogs WHERE UsedInviteCode = ?"
    rowsUsedInviteCodes, err := db.Query(usedInviteCodesQuery, inviteCode)
    if err != nil && err != sql.ErrNoRows {
        fmt.Printf("Error fetching used invite codes: %v\n", err)
    }
    defer rowsUsedInviteCodes.Close()

    // 从 users 表中获取 Name 和 Username
    userQuery := "SELECT username, name FROM users WHERE used_invite_code = ?"
    rowsUsers, err := db.Query(userQuery, inviteCode)
    if err != nil {
        fmt.Printf("Error fetching user names: %v\n", err)
        return
    }
    defer rowsUsers.Close()

    type InviteData struct {
        Name   string
        Amount float64
    }

    inviteCodeMap := make(map[string]InviteData)
    for rowsUsers.Next() {
        var inviteUsername, inviteName string
        if err := rowsUsers.Scan(&inviteUsername, &inviteName); err != nil {
            fmt.Printf("Error scanning user names: %v\n", err)
            continue
        }

        // 默认金额为0
        inviteData := InviteData{
            Name:   inviteName,
            Amount: 0,
        }

        inviteCodeMap[inviteUsername] = inviteData
    }

    // 更新金额
    for rowsUsedInviteCodes.Next() {
        var inviteUsername string
        var inviteAmount float64
        if err := rowsUsedInviteCodes.Scan(&inviteUsername, &inviteAmount); err != nil {
            fmt.Printf("Error scanning used invite codes: %v\n", err)
            continue
        }
        if data, exists := inviteCodeMap[inviteUsername]; exists {
            data.Amount += inviteAmount
            inviteCodeMap[inviteUsername] = data
        } else {
            inviteCodeMap[inviteUsername] = InviteData{
                Name:   "",  // 如果在用户表中找不到名字，默认为空字符串
                Amount: inviteAmount,
            }
        }
    }

    var usedInviteCodes []map[string]interface{}
    for username, data := range inviteCodeMap {
        usedInviteCodes = append(usedInviteCodes, map[string]interface{}{
            "Username": username,
            "Name":     data.Name,
            "Amount":   data.Amount,
        })
    }
    
    messageQuery := `SELECT username, content, avatar_path, created_at FROM message_board ORDER BY created_at DESC`
    rowsMessages, err := db.Query(messageQuery)
    if err != nil {
        fmt.Printf("Error fetching messages: %v\n", err)
        return
    }
    defer rowsMessages.Close()

    var messages []MessageBoard
    for rowsMessages.Next() {
        var msg MessageBoard
        if err := rowsMessages.Scan(&msg.Username, &msg.Content, &msg.AvatarPath, &msg.CreatedAt); err != nil {
            fmt.Printf("Error scanning message: %v\n", err)
            continue
        }
        messages = append(messages, msg)
    }

    var favoritePlaymates []string
    favoriteQuery := `SELECT PlaymateID FROM Favorites WHERE Username = ?`
    rowsFavorites, err := db.Query(favoriteQuery, username)
    if err != nil {
        fmt.Printf("Error fetching favorites: %v\n", err)
    } else {
        defer rowsFavorites.Close()
        for rowsFavorites.Next() {
            var playmateID string
            if err := rowsFavorites.Scan(&playmateID); err != nil {
                fmt.Printf("Error scanning favorite playmate: %v\n", err)
            } else {
                favoritePlaymates = append(favoritePlaymates, playmateID)
            }
        }
    }
    favoritePlaymatesJSON, err := json.Marshal(favoritePlaymates)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize ranks"})
        return
    } 
    
    data := gin.H{
        "username":             username,
        "name":                 name,
        "ai_group":             aiGroup,
        "stars_count":          starsCount,
        "ContactingOrders":     contactingOrders,
        "OngoingOrders":        ongoingOrders,
        "CompletedOrders":      completedOrders,
        "current_event_text":   eventText,
        "play_price":           replacedText,
        "ranks":                string(ranksJSON),
        "playmates":            playmates,
        "total_frozen_star_cost": totalFrozenStarCost,
        "invite_code":          inviteCode,
        "used_invite_code":     usedInviteCode,
        "used_invite_codes":    usedInviteCodes,
        "messages":             messages,
        "favorite_playmates":   string(favoritePlaymatesJSON),
    }
    
    // 添加交易物品数据
    if len(tradeItems) > 0 {
        data["trade_items"] = tradeItems
    }
    if len(userTradeItems) > 0 {
        data["UserTradeItems"] = userTradeItems
    }
    
    // 添加新用户信息（如果是新用户）
    if isNewUser {
        data["is_new_user"] = true
        data["new_user_password"] = newUserPassword
    }
    
    // 渲染HTML页面
    c.HTML(http.StatusOK, "laoban.html", data)
})
    r.POST("/report", func(c *gin.Context) {
        var reportData struct {
            Reason   string `json:"reason"`
            Details  string `json:"details"`
            BridgeID string `json:"bridgeID"`
        }
    
        if err := c.BindJSON(&reportData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法解析请求"})
            return
        }
    
        var groupUserNickName, weChatUser string
    
        // 查询 Bridges 表中的相关信息
        err := db.QueryRow("SELECT GroupUserNickName, WeChatUser FROM Bridges WHERE ID = ?", reportData.BridgeID).Scan(&groupUserNickName, &weChatUser)
        if err != nil {
            if err == sql.ErrNoRows {
                c.JSON(http.StatusBadRequest, gin.H{"error": "无效的 BridgeID"})
            } else {
                log.Printf("查询 Bridges 表失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询 Bridges 表失败"})
            }
            return
        }
    
        // 生成举报消息
        reportMessage := fmt.Sprintf("举报人：%s，举报打手：%s，原因：%s，详细情况：%s", groupUserNickName, weChatUser, reportData.Reason, reportData.Details)
        sendTextMessage(reportMessage, "国1车队联系员-梦奇（24小时ai在）")
        c.JSON(http.StatusOK, gin.H{"message": "举报成功"})
    })    
	// 说明页面路由
	r.GET("/recharge_info", func(c *gin.Context) {
		c.HTML(http.StatusOK, "recharge_info.html", nil)
	})    
    r.POST("/exchange", func(c *gin.Context) {
        var requestData struct {
            Amount         float64 `json:"amount"`
            UsedInviteCode string  `json:"used_invite_code"`
            Username       string  `json:"username"`
            Name           string  `json:"name"`
            AIGroup        string  `json:"ai_group"`
        }
        session := sessions.Default(c)
        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法解析请求"})
            return
        }
    
        // 计算兑换的星卷数量
        stars := int(math.Ceil(requestData.Amount / 5))
    
        // 更新会话中的星卷数量
        starsCount := session.Get("stars_count").(int)
        newStarsCount := starsCount + stars
        session.Set("stars_count", newStarsCount)
        if err := session.Save(); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法保存会话"})
            return
        }
    
        // 更新数据库中的星卷数量
        if requestData.AIGroup == "" {
            // 如果没有AI群，更新用户表中的星卷数量
            if _, err := db.Exec("UPDATE users SET star_journal = ? WHERE username = ?", newStarsCount, requestData.Username); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新数据库失败"})
                return
            }
        } else {
            // 检查用户在指定群组中是否已有星卷记录
            var existingStars int
            err := db.QueryRow("SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?", requestData.AIGroup, requestData.Name).Scan(&existingStars)
            
            if err != nil && err != sql.ErrNoRows {
                log.Printf("查询星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", requestData.AIGroup, requestData.Name, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询星卷记录失败"})
                return
            }
    
            if err == sql.ErrNoRows {
                // 插入新记录
                _, err = db.Exec("INSERT INTO member_stars (GroupID, UserName, StarsCount) VALUES (?, ?, ?)", requestData.AIGroup, requestData.Name, stars)
                if err != nil {
                    log.Printf("插入新的星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", requestData.AIGroup, requestData.Name, err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "插入新的星卷记录失败"})
                    return
                }
                log.Printf("插入新的星卷记录成功: 群组=%s, 昵称=%s, 星卷数=%d", requestData.AIGroup, requestData.Name, stars)
            } else {
                // 更新现有记录
                _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount + ? WHERE GroupID = ? AND UserName = ?", stars, requestData.AIGroup, requestData.Name)
                if err != nil {
                    log.Printf("更新星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", requestData.AIGroup, requestData.Name, err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷记录失败"})
                    return
                }
                log.Printf("更新星卷记录成功: 群组=%s, 昵称=%s, 新增星卷数=%d", requestData.AIGroup, requestData.Name, stars)
            }
        }
        
        // 删除UserRechargeLogs表中所有与指定Username相关的记录
        if _, err := db.Exec("DELETE FROM UserRechargeLogs WHERE UsedInviteCode = ?", requestData.UsedInviteCode); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "删除记录失败"})
            return
        }

        // 查询星卷数量
        xj := queryMemberStars(db, requestData.AIGroup, requestData.Name)
        bridge := findBridge("网站", requestData.Name)
        if bridge != nil && bridge.IsActive {
            // 如果订单类型是代练，星卷数翻倍
            if bridge.OrderType == "代练" && !strings.Contains(bridge.Msg, "巅峰") {
                xj *= 2
            }
            var initialRanks []string
            // 从bridge.Msg中提取最大升级次数
            re := regexp.MustCompile(",最多打(\\d+)(♥|净胜)")
            matches := re.FindStringSubmatch(bridge.Msg)
            var maxUpgrades int
            if len(matches) > 1 {
                maxUpgrades, _ = strconv.Atoi(matches[1])
            }

            ranksCosts, err := getAllRanksAndCosts(db)
            if err != nil {
                fmt.Printf("Error getting ranks and prices: %v\n", err)
                return
            }

            // 对ranksCosts按照段位长度进行排序
            var ranks []string
            for _, rankCost := range ranksCosts {
                ranks = append(ranks, rankCost[0]) // 添加段位名称
            }

            sort.Slice(ranks, func(i, j int) bool {
                return len(ranks[i]) > len(ranks[j])
            })

            // 解析 bridge.Msg 来获取匹配的段位
            var matchedRanks []string
            input := bridge.Msg
            for _, rank := range ranks {
                rankOccurrences := strings.Count(input, rank)
                for i := 0; i < rankOccurrences; i++ {
                    matchedRanks = append(matchedRanks, rank)
                    input = strings.Replace(input, rank, "", 1)
                }
            }

            initialRanks = matchedRanks
            fmt.Printf("初始段位: %v\n", initialRanks)
            finalRanks, upgrades, err := calculateMaxUpgradesAndRank(db, initialRanks, int(xj))
            if err != nil {
                fmt.Printf("无法计算升级: %v\n", err)
                return
            }
            fmt.Printf("升级星数: %v\n", upgrades)
            fmt.Printf("升级后的段位: %v\n", finalRanks)
            // 向桥接中记录的微信用户发送续单信息
            weChatUser := bridge.WeChatUser
            weChatUserName, err := findUserNameByNickName(weChatUser)
            if err != nil {
                fmt.Printf("根据昵称查找用户失败: %v\n", err)
                return
            }
            actualUpgrades := upgrades - maxUpgrades
            sendTextMessage(fmt.Sprintf("老板额外续单 %d 星，总共打 %d 星，继续打", int(actualUpgrades), upgrades), weChatUserName)
        }
        // 回复兑换成功消息
        c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("您成功兑换了 %d 星卷！您当前的星卷数量为：%d", stars, int(xj))})
    })    
    
    r.POST("/recharge", func(c *gin.Context) {
        var requestData struct {
            RechargeCode   string `json:"recharge_code"`
            UsedInviteCode string `json:"used_invite_code"`
            Username       string `json:"username"`
            Name           string `json:"name"`
            AIGroup        string `json:"ai_group"`
        }
        session := sessions.Default(c)
        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法解析请求"})
            return
        }
    
        // 正则表达式匹配“兑换码：”后的数字或者18位或19位纯数字
        rechargeCodeMatch := regexp.MustCompile(`兑换码：(\d+)|\b\d{18,19}\b`).FindStringSubmatch(requestData.RechargeCode)
        var code string
        if len(rechargeCodeMatch) > 1 {
            if rechargeCodeMatch[1] != "" {
                code = rechargeCodeMatch[1] // 匹配“兑换码：”后的数字
            } else if rechargeCodeMatch[0] != "" {
                code = rechargeCodeMatch[0] // 匹配纯18位或19位数字
            }
    
            amount, err := redeemRechargeCode(db, code) // 兑换码兑换
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "充值失败"})
                return
            }
            
            starsCount := session.Get("stars_count").(int)
            // 更新星卷数量
            stars, err := updateStarsCount(db, requestData.AIGroup, requestData.Name, amount)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败"})
                return
            }
    
            // 查询星卷数量
            xj := queryMemberStars(db, requestData.AIGroup, requestData.Name)
    
            // 回复充值成功消息
            c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("您成功兑换了 %d 星卷！您当前的星卷数量为：%d", stars, int(xj))})
            
            // 更新会话中的星卷数量
            newStarsCount := starsCount + stars
            session.Set("stars_count", newStarsCount)
            if err := session.Save(); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "无法保存会话"})
                return
            }
    
            // 更新数据库中的星卷数量
            if requestData.AIGroup == "" {
                _, err := db.Exec("UPDATE users SET star_journal = ? WHERE username = ?", newStarsCount, requestData.Username)
                if err != nil {
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "更新数据库失败"})
                    return
                }
            }
    
            // 插入使用该充值码的用户信息到 UserRechargeLogs 表
            _, err = db.Exec("INSERT INTO UserRechargeLogs (Name, Username, Amount, UsedInviteCode) VALUES (?, ?, ?, ?)", requestData.Name, requestData.Username, amount*0.1, requestData.UsedInviteCode)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "记录充值码使用信息失败"})
                return
            }
    
            // 查找与发送者相关联的桥接对象
            bridge := findBridge("网站", requestData.Name)
            if bridge != nil && bridge.IsActive {
                // 如果订单类型是代练，星卷数翻倍
                if bridge.OrderType == "代练" && !strings.Contains(bridge.Msg, "巅峰") {
                    xj *= 2
                }
                var initialRanks []string
                // 从bridge.Msg中提取最大升级次数
                re := regexp.MustCompile(",最多打(\\d+)(♥|净胜)")
                matches := re.FindStringSubmatch(bridge.Msg)
                var maxUpgrades int
                if len(matches) > 1 {
                    maxUpgrades, _ = strconv.Atoi(matches[1])
                }
    
                ranksCosts, err := getAllRanksAndCosts(db)
                if err != nil {
                    fmt.Printf("Error getting ranks and prices: %v\n", err)
                    return
                }
    
                // 对ranksCosts按照段位长度进行排序
                var ranks []string
                for _, rankCost := range ranksCosts {
                    ranks = append(ranks, rankCost[0]) // 添加段位名称
                }
    
                sort.Slice(ranks, func(i, j int) bool {
                    return len(ranks[i]) > len(ranks[j])
                })
    
                // 解析 bridge.Msg 来获取匹配的段位
                var matchedRanks []string
                input := bridge.Msg
                for _, rank := range ranks {
                    rankOccurrences := strings.Count(input, rank)
                    for i := 0; i < rankOccurrences; i++ {
                        matchedRanks = append(matchedRanks, rank)
                        input = strings.Replace(input, rank, "", 1)
                    }
                }
    
                initialRanks = matchedRanks
                fmt.Printf("初始段位: %v\n", initialRanks)
                finalRanks, upgrades, err := calculateMaxUpgradesAndRank(db, initialRanks, int(xj))
                if err != nil {
                    fmt.Printf("无法计算升级: %v\n", err)
                    return
                }
                fmt.Printf("升级星数: %v\n", upgrades)
                fmt.Printf("升级后的段位: %v\n", finalRanks)
                // 向桥接中记录的微信用户发送续单信息
                weChatUser := bridge.WeChatUser
                weChatUserName, err := findUserNameByNickName(weChatUser)
                if err != nil {
                    fmt.Printf("根据昵称查找用户失败: %v\n", err)
                    return
                }
                actualUpgrades := upgrades - maxUpgrades
                sendTextMessage(fmt.Sprintf("老板额外续单 %d 星，总共打 %d 星，继续打", int(actualUpgrades), upgrades), weChatUserName)
            }
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无效的充值码"})
            return
        }
    })    

    r.POST("/upload-avatar", func(c *gin.Context) {
        username := c.PostForm("username")
        file, err := c.FormFile("avatar")
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
    
        savePath := "./shuoming/hut/"
        if err := os.MkdirAll(savePath, os.ModePerm); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
    
        fileName := fmt.Sprintf("%s.jpg", username) // 将文件名后缀改成jpg
        filePath := filepath.Join(savePath, fileName)
    
        if err := c.SaveUploadedFile(file, filePath); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "fileName": fileName,
        })
    })    
    
    r.POST("/delete-auction", func(c *gin.Context) {
        var data struct {
            AuctionId string `json:"auctionId"`
        }
        if err := c.BindJSON(&data); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "Invalid request"})
            return
        }
    
        // 删除数据库中的拍卖记录
        if _, err := db.Exec("DELETE FROM trade_items WHERE ID = ?", data.AuctionId); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "Failed to delete auction"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"success": true})
    })
    
    r.POST("/submit_auction", func(c *gin.Context) {
        var auctionData struct {
            User            string `json:"user"`
            Username        string `json:"username"`
            ItemName        string `json:"itemName"`
            ItemPrice       string `json:"itemPrice"`
            ItemQuantity    string `json:"itemQuantity"`
            ItemDescription string `json:"itemDescription"`
        }
    
        if err := c.ShouldBindJSON(&auctionData); err != nil {
            log.Printf("解析请求数据失败: %v\n", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
    
        // 检查并设置默认值
        if auctionData.User == "" {
            auctionData.User = "未登录账户" // 设置默认用户名
        }
        if auctionData.Username == "" {
            auctionData.Username = "anonymous" // 设置默认 username
        }
    
        // 从 JSON 数据中提取字段
        seller := auctionData.User
        itemName := strings.ReplaceAll(strings.TrimSpace(strings.ToLower(auctionData.ItemName)), "的", "")
        description := strings.ReplaceAll(strings.TrimSpace(strings.ToLower(auctionData.ItemDescription)), "的", "")
        price := auctionData.ItemPrice
        quantity := auctionData.ItemQuantity
    
        // 定义插入SQL语句
        insertStmt := `INSERT INTO trade_items (seller, buyers, group_id, item_name, description, price, quantity, image_file_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
    
        // 执行插入操作，并获取生成的ID
        result, err := db.Exec(insertStmt, seller, "", "", itemName, description, price, quantity, "")
        if err != nil {
            log.Printf("插入交易品失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "插入交易品失败"})
            return
        }
    
        insertID, err := result.LastInsertId()
        if err != nil {
            log.Printf("获取插入ID失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取插入ID失败"})
            return
        }
    
        // 检查 ItemName 或 ItemDescription 是否包含预购商品的文本
        rows, err := db.Query("SELECT username, buying FROM pre_orders")
        if err != nil {
            log.Printf("查询预购商品失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询预购商品失败"})
            return
        }
        defer rows.Close()
    
        for rows.Next() {
            var preOrderUsername, buying string
            err := rows.Scan(&preOrderUsername, &buying)
            if err != nil {
                log.Printf("扫描预购商品失败: %v\n", err)
                continue
            }
    
            buying = strings.ReplaceAll(strings.TrimSpace(strings.ToLower(buying)), "的", "")
    
            if strings.Contains(itemName, buying) || strings.Contains(description, buying) {
                var openid string
                err = db.QueryRow("SELECT openid FROM users WHERE username = ?", preOrderUsername).Scan(&openid)
                if err != nil {
                    log.Printf("查询openid失败: %v\n", err)
                    continue
                }
    
                // 模板消息内容
                data := make(map[string]TemplateData)
                data["thing15"] = TemplateData{Value: buying, Color: "#173177"}               // 预约项目
                data["amount7"] = TemplateData{Value: price, Color: "#FF0000"}                // 订单金额
                data["thing20"] = TemplateData{Value: "点击这里，直接查看详情，进行联系", Color: "#008000"} // 门店地址
    
                // 构建模板消息结构体
                templateMessage := TemplateMessage{
                    Touser:     openid,
                    TemplateID: "aA-FcQczfNsE9LoAccBGL6R9RIOixU4oXpJ21KkMFV8", // 替换为你的模板 ID
                    URL:        fmt.Sprintf("https://www.moki-flanke.icu/trade/%d", insertID), // 设置跳转链接
                    Data:       data,
                }
    
                // 获取 Access Token 的函数，替换为你的实现方式
                accessToken, err := getAccessToken()
                if err != nil {
                    log.Printf("获取Access Token失败: %v\n", err)
                    continue
                }
    
                // 发送模板消息
                err = sendTemplateMessage(accessToken, templateMessage)
                if err != nil {
                    log.Printf("发送模板消息失败: %v\n", err)
                    continue
                }
            }
        }
    
        c.JSON(http.StatusOK, gin.H{"status": "success"})
    })
    
    
    r.GET("/trade/:id", func(c *gin.Context) {
        id := c.Param("id")

        var tradeItem TradeItem
        err := db.QueryRow("SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items WHERE id = ?", id).Scan(
            &tradeItem.ID,
            &tradeItem.Seller,
            &tradeItem.Buyers,
            &tradeItem.ItemName,
            &tradeItem.Description,
            &tradeItem.Price,
            &tradeItem.Quantity,
            &tradeItem.ImageFileName,
        )
        if err != nil {
            log.Printf("查询交易品信息失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询交易品信息失败"})
            return
        }

        // 渲染HTML模板，并传递交易品数据
        c.HTML(http.StatusOK, "trade.html", gin.H{
            "ID":            tradeItem.ID,
            "Seller":        tradeItem.Seller,
            "Buyers":        tradeItem.Buyers,
            "ItemName":      tradeItem.ItemName,
            "Description":   tradeItem.Description,
            "Price":         tradeItem.Price,
            "Quantity":      tradeItem.Quantity,
            "ImageFileName": tradeItem.ImageFileName,
        })
    })
    // 获取所有交易品
    r.GET("/trade", func(c *gin.Context) {
        rows, err := db.Query("SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items")
        if err != nil {
            log.Printf("查询所有交易品信息失败: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询所有交易品信息失败"})
            return
        }
        defer rows.Close()

        var tradeItems []TradeItem
        for rows.Next() {
            var tradeItem TradeItem
            err := rows.Scan(
                &tradeItem.ID,
                &tradeItem.Seller,
                &tradeItem.Buyers,
                &tradeItem.ItemName,
                &tradeItem.Description,
                &tradeItem.Price,
                &tradeItem.Quantity,
                &tradeItem.ImageFileName,
            )
            if err != nil {
                log.Printf("扫描交易品信息失败: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "扫描交易品信息失败"})
                return
            }

            // 只有当 ImageFileName 为空时，才添加到列表中
            if tradeItem.ImageFileName == "" {
                tradeItems = append(tradeItems, tradeItem)
            }
        }

        // 渲染HTML模板，并传递所有符合条件的交易品数据
        c.HTML(http.StatusOK, "trade.html", gin.H{
            "TradeItems": tradeItems,
        })
    })
    r.POST("/search", func(c *gin.Context) {
        var req struct {
            Text string `json:"text"`
        }
        if err := c.BindJSON(&req); err != nil {
            log.Printf("Invalid request: %v\n", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
            return
        }
    
        text := req.Text
        log.Printf("Received search text: %s\n", text)
    
        if len(text) < 2 {
            log.Printf("Search text length is less than 2: %s\n", text)
            c.JSON(http.StatusBadRequest, gin.H{"error": "传入的文本长度必须至少为2"})
            return
        }
    
        if strings.Contains(text, "码") {
            log.Println("Searching for the latest item with '码'...")
            var item TradeItem
    
            // 查询 id 最大的条目
            row := db.QueryRow(`SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name 
                                FROM trade_items WHERE item_name LIKE ? OR description LIKE ? 
                                ORDER BY id DESC LIMIT 1`, "%"+text+"%", "%"+text+"%")
    
            if err := row.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
                if err == sql.ErrNoRows {
                    log.Println("No matches found with '码'")
                    c.JSON(http.StatusNotFound, gin.H{"error": "没有匹配的交易品"})
                    return
                }
                log.Printf("Data scan failed: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据扫描失败"})
                return
            }
    
            // 减少数量
            if item.Quantity > 0 {
                item.Quantity--
                _, err := db.Exec(`UPDATE trade_items SET quantity = ? WHERE id = ?`, item.Quantity, item.ID)
                if err != nil {
                    log.Printf("Update failed: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
                    return
                }
    
                // 如果数量减小到 0，删除该条目
                if item.Quantity == 0 {
                    _, err := db.Exec(`DELETE FROM trade_items WHERE id = ?`, item.ID)
                    if err != nil {
                        log.Printf("Delete failed: %v\n", err)
                        c.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败"})
                        return
                    }
                }
            }
    
            log.Printf("Returning the latest item with '码': %v\n", item)
            c.JSON(http.StatusOK, item)
            return
        }
    
        var items []TradeItem
    
        // 查询所有 trade_items
        rows, err := db.Query(`SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items`)
        if err != nil {
            log.Printf("Query failed: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
            return
        }
        defer rows.Close()
    
        log.Println("Searching in item_name...")
        // 检查 item_name 中的匹配
        for rows.Next() {
            var item TradeItem
            if err := rows.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
                log.Printf("Data scan failed: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据扫描失败"})
                return
            }
    
            if strings.Contains(item.ItemName, text) {
                log.Printf("Found match in item_name: %v\n", item)
                items = append(items, item)
            }
        }
    
        // 如果在 item_name 中没有找到匹配项，再检查 description 中的匹配
        if len(items) == 0 {
            log.Println("No matches found in item_name, searching in description...")
            rows, err = db.Query(`SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items`)
            if err != nil {
                log.Printf("Query failed: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
                return
            }
            defer rows.Close()
    
            for rows.Next() {
                var item TradeItem
                if err := rows.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
                    log.Printf("Data scan failed: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "数据扫描失败"})
                    return
                }
    
                if strings.Contains(item.Description, text) {
                    log.Printf("Found match in description: %v\n", item)
                    items = append(items, item)
                }
            }
        }
    
        // 如果在两者中都未找到匹配项，并且文本包含了逗号，则去掉逗号后重新查询
        if len(items) == 0 && strings.Contains(text, "，") {
            log.Println("No matches found, trying again without commas...")
            text = strings.ReplaceAll(text, "的", "")
    
            rows, err = db.Query(`SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items`)
            if err != nil {
                log.Printf("Query failed: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
                return
            }
            defer rows.Close()
    
            log.Println("Searching in item_name without commas...")
            for rows.Next() {
                var item TradeItem
                if err := rows.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
                    log.Printf("Data scan failed: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "数据扫描失败"})
                    return
                }
    
                if strings.Contains(item.ItemName, text) {
                    log.Printf("Found match in item_name: %v\n", item)
                    items = append(items, item)
                }
            }
    
            if len(items) == 0 {
                log.Println("No matches found in item_name, searching in description without commas...")
                rows, err = db.Query(`SELECT id, seller, buyers, item_name, description, price, quantity, image_file_name FROM trade_items`)
                if err != nil {
                    log.Printf("Query failed: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
                    return
                }
                defer rows.Close()
    
                for rows.Next() {
                    var item TradeItem
                    if err := rows.Scan(&item.ID, &item.Seller, &item.Buyers, &item.ItemName, &item.Description, &item.Price, &item.Quantity, &item.ImageFileName); err != nil {
                        log.Printf("Data scan failed: %v\n", err)
                        c.JSON(http.StatusInternalServerError, gin.H{"error": "数据扫描失败"})
                        return
                    }
    
                    if strings.Contains(item.Description, text) {
                        log.Printf("Found match in description: %v\n", item)
                        items = append(items, item)
                    }
                }
            }
        }
    
        if len(items) == 0 {
            log.Println("No matches found in both item_name and description")
            c.JSON(http.StatusNotFound, gin.H{"error": "没有匹配的交易品"})
            return
        }
    
        log.Printf("Returning %d matching items\n", len(items))
        c.JSON(http.StatusOK, items)
    })
    
    r.POST("/cancel_preorder", func(c *gin.Context) {
        var cancelInfo struct {
            Username string `form:"username"`
            Buying   string `form:"buying"`
        }
        if err := c.ShouldBind(&cancelInfo); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "表单信息不完整"})
            return
        }
        
        // 确保 username 不为空
        if cancelInfo.Username == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名不能为空"})
            return
        }
    
        // 去掉 Buying 字段中的所有“的”字符
        cleanBuying := strings.ReplaceAll(cancelInfo.Buying, "的", "")
    
        var result sql.Result
        var err error
        var rowsAffected int64
    
        if cleanBuying == "" {
            // 如果 buying 为空，则删除该用户的所有预购记录
            result, err = db.Exec("DELETE FROM pre_orders WHERE username = ?", cancelInfo.Username)
        } else {
            // 尝试仅删除指定的预购记录
            result, err = db.Exec("DELETE FROM pre_orders WHERE username = ? AND buying = ?", cancelInfo.Username, cleanBuying)
            if err == nil {
                // 检查删除操作是否成功
                rowsAffected, err = result.RowsAffected()
                if err != nil {
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "取消预购失败"})
                    return
                }
    
                if rowsAffected == 0 {
                    // 如果指定的预购记录未找到，则删除该用户的所有预购记录
                    result, err = db.Exec("DELETE FROM pre_orders WHERE username = ?", cancelInfo.Username)
                }
            }
        }
        
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "取消预购失败"})
            return
        }
    
        // 检查删除操作是否成功
        rowsAffected, err = result.RowsAffected()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "取消预购失败"})
            return
        }
        
        if rowsAffected == 0 {
            c.JSON(http.StatusNotFound, gin.H{"error": "没有找到需要取消的预购记录"})
            return
        }
    
        // 返回取消预购成功信息
        c.JSON(http.StatusOK, gin.H{"message": "取消预购成功"})
    })    
    
    r.POST("/yugou", func(c *gin.Context) {
        var loginInfo struct {
            Username string `form:"username"`
            Password string `form:"password"`
            Buying   string `form:"buying"`
        }
        if err := c.ShouldBind(&loginInfo); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "表单信息不完整"})
            return
        }
    
        // 查询数据库以获取用户详细信息，包括邀请码和被使用的邀请码
        var hashedPassword, aiGroup, starJournal, name, inviteCode, usedInviteCode string
        err := db.QueryRow("SELECT password, ai_group, star_journal, name, invite_code, used_invite_code FROM users WHERE username = ?", loginInfo.Username).Scan(&hashedPassword, &aiGroup, &starJournal, &name, &inviteCode, &usedInviteCode)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        // 检查加密的密码是否与数据库中的密码匹配
        if err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(loginInfo.Password)); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户名或密码错误"})
            return
        }
    
        session := sessions.Default(c)
        session.Set("user", loginInfo.Username)
        session.Set("name", name)
        session.Set("userIP", c.ClientIP())
        session.Set("ai_group", aiGroup)
        session.Set("invite_code", inviteCode)          // 设置用户的邀请码
        session.Set("used_invite_code", usedInviteCode) // 设置用户注册时使用的邀请码
    
        if aiGroup == "" {
            session.Set("stars_count", starJournal)
        } else {
            var starsCount int
            err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE UserName = ? AND GroupID = ?", name, aiGroup).Scan(&starsCount)
            if err != nil && err != sql.ErrNoRows {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询星星数失败"})
                return
            }
            session.Set("stars_count", starsCount)
        }
    
        session.Save()
    
        // 去掉 Buying 字段中的所有“的”字符
        cleanBuying := strings.ReplaceAll(loginInfo.Buying, "的", "")
    
        // 新建预购表，并存储用户的username和buying信息
        _, err = db.Exec("INSERT INTO pre_orders (username, buying) VALUES (?, ?)", loginInfo.Username, cleanBuying)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "存储预购信息失败"})
            return
        }
    
        // 返回登录成功信息，不需要重定向
        c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
    })
    
    r.POST("/submit_order", func(c *gin.Context) {
        var orderData struct {
            Username    string   `json:"username"`
            OrderType   string   `json:"orderType"`
            Orders      []string `json:"orders"`
            StarsCount  int      `json:"starsCount"`
            TargetRanks []string `json:"targetRanks"`
            GameName    string   `json:"gameName,omitempty"` // 新增字段
        }
    
        if err := c.BindJSON(&orderData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法安排，核对信息"})
            return
        }
        fmt.Printf("游戏名字：%s", orderData.GameName)
        // 去掉 "来个" 两个字符
        if strings.HasPrefix(orderData.OrderType, "来个") {
            orderData.OrderType = strings.TrimPrefix(orderData.OrderType, "来个")
        }
    
        // 验证段位并计算总冻结星卷
        canProceed, totalFreezeStars, err := validateRank(db, orderData.OrderType, orderData.TargetRanks, orderData.Orders, orderData.StarsCount)
        if err != nil {
            fmt.Printf("Error validating rank: %v\n", err) // 打印错误信息
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Error validating rank", "details": err.Error()})
            return
        }
        if !canProceed {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法安排，核对信息"})
            return
        }
    
        // 检查冻结的星卷是否小于等于0
        if totalFreezeStars <= 0 {
            c.JSON(http.StatusBadRequest, gin.H{"error": "请输入您的目标段位"})
            return
        }
    
        fmt.Printf("Validation successful, total freeze stars: %d\n", totalFreezeStars)
        // 确保 generateContent 和 createBridge 函数工作正常
        content, err := generateContent(db, orderData.Orders, orderData.OrderType, orderData.StarsCount, orderData.TargetRanks)
        if err != nil {
            fmt.Printf("Error generating content: %v\n", err) // 打印错误信息
            c.JSON(http.StatusInternalServerError, gin.H{"error": "生成内容失败", "details": err.Error()})
            return
        }
        if orderData.GameName != "" {
            globalGameIDMap[content] = orderData.GameName
        }
        createBridge("网站", "网站", orderData.Username, content, orderData.OrderType, totalFreezeStars)
    
        // 更新数据库中的星卷数量
        var aiGroup, Name string
        var starsCount int
        err = db.QueryRow("SELECT ai_group, name FROM users WHERE username = ?", orderData.Username).Scan(&aiGroup, &Name)
        if err != nil {
            fmt.Printf("Error querying AI group: %v\n", err) // 打印错误信息
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询AI群组失败", "details": err.Error()})
            return
        }
    
        if aiGroup == "" {
            _, err = db.Exec("UPDATE users SET star_journal = star_journal - ? WHERE username = ?", totalFreezeStars, orderData.Username)
            if err != nil {
                fmt.Printf("Error updating stars for user: %v\n", err) // 打印错误信息
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                return
            }
        } else {
            _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount - ? WHERE UserName = ? AND GroupID = ?", totalFreezeStars, Name, aiGroup)
            if err != nil {
                fmt.Printf("Error updating stars for AI group: %v\n", err) // 打印错误信息
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                return
            }
        }
    
        // 获取更新后的星卷数量
        if aiGroup == "" {
            err = db.QueryRow("SELECT star_journal FROM users WHERE username = ?", orderData.Username).Scan(&starsCount)
        } else {
            err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE UserName = ? AND GroupID = ?", Name, aiGroup).Scan(&starsCount)
        }
        if err != nil {
            fmt.Printf("Error fetching updated stars count: %v\n", err) // 打印错误信息
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取更新后的星卷数量失败", "details": err.Error()})
            return
        }
        // 更新session中的星卷数量
        session := sessions.Default(c)
        session.Set("stars_count", starsCount)
        err = session.Save()
        if err != nil {
            fmt.Printf("Error saving session: %v\n", err) // 打印错误信息
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新session失败", "details": err.Error()})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "提交成功", "freezeStars": totalFreezeStars, "canProceed": true, "remainingStars": starsCount})
    })     

    r.GET("/get_openid", func(c *gin.Context) {
        code := c.Query("code")
        username := c.Query("username")
        if code == "" || username == "" {
            log.Println("No code or username provided")
            c.JSON(http.StatusBadRequest, gin.H{"error": "No code or username provided"})
            return
        }
    
        url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
    
        resp, err := http.Get(url)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get openid"})
            return
        }
        defer resp.Body.Close()
    
        body, err := io.ReadAll(resp.Body)
        if err != nil {
            log.Printf("Failed to read response body: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read response body"})
            return
        }
    
        var openIDResp OpenIDResponse
        if err := json.Unmarshal(body, &openIDResp); err != nil {
            log.Printf("Failed to unmarshal response: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to unmarshal response"})
            return
        }
    
        if openIDResp.OpenID == "" {
            log.Printf("Failed to get openid, errmsg: %s", openIDResp.ErrMsg)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get openid", "errmsg": openIDResp.ErrMsg})
            return
        }
    
        log.Printf("Successfully got openid: %s", openIDResp.OpenID) // 打印成功获取的 openid
    
        stmt, err := db.Prepare("UPDATE users SET openid = ? WHERE username = ?")
        if err != nil {
            log.Printf("Failed to prepare SQL statement: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to prepare SQL statement"})
            return
        }
        defer stmt.Close()
    
        _, err = stmt.Exec(openIDResp.OpenID, username)
        if err != nil {
            log.Printf("Failed to execute SQL statement: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to execute SQL statement"})
            return
        }
    
        log.Printf("Successfully updated openid for username: %s", username)
    
        c.JSON(http.StatusOK, openIDResp)
    })
        
    r.POST("/change_order", func(c *gin.Context) {
        var requestData struct {
            OrderID string   `json:"orderId"`
            Ranks   []string `json:"ranks"`
            Stars   []string `json:"stars"`
        }
        
        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法解析请求"})
            return
        }
        
        // 获取订单信息，包括 GroupUserNickName
        var order struct {
            Msg               string
            OrderType         string
            WeChatUser        string
            GroupUserNickName string
            GroupName         string
            GroupID           string  // 添加GroupID字段，用于代发订单
        }
        err := db.QueryRow("SELECT Msg, OrderType, WeChatUser, GroupUserNickName, GroupName, GroupID FROM Bridges WHERE ID = ?", requestData.OrderID).Scan(
            &order.Msg, 
            &order.OrderType, 
            &order.WeChatUser, 
            &order.GroupUserNickName,
            &order.GroupName,
            &order.GroupID,
        )
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单信息失败"})
            return
        }
        
        // 查询BridgeMessages表中该BridgeID最早的消息作为orderData.BossId
        var orderDataBossId string
        err = db.QueryRow("SELECT Message FROM BridgeMessages WHERE BridgeID = ? ORDER BY Timestamp ASC LIMIT 1", requestData.OrderID).Scan(&orderDataBossId)
        if err != nil {
            fmt.Printf("查询BridgeID %s 的最早消息失败: %v\n", requestData.OrderID, err)
            // 如果找不到消息，使用原始订单内容作为BossId
            orderDataBossId = order.Msg
        }
        
        // 检查是否是代发订单，如果是代发订单，检查消息中是否包含VIP标记
        if order.GroupName == "代发" {
            // 定义VIP标记列表
            vipMarkers := []string{"#秒开车队来", "#技术娱乐陪接", "#小姐姐接", "#通天代接"}
            
            // 检查消息中是否包含任何VIP标记
            isVipOrder := false
            for _, marker := range vipMarkers {
                if strings.Contains(order.Msg, marker) {
                    isVipOrder = true
                    break
                }
            }
            
            // 如果不是VIP订单，返回错误
            if !isVipOrder {
                c.JSON(http.StatusForbidden, gin.H{
                    "error": "非VIP代发单不允许更换",
                    "message": "非VIP代发单不允许更换，请重新发单或者联系发单",
                })
                return
            }
        }
        
        // 更新 IsActive 字段为 false
        _, err = db.Exec("UPDATE Bridges SET IsActive = 0 WHERE ID = ?", requestData.OrderID)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新订单状态失败"})
            return
        }
        
        // 循环处理每一个 WeChatUser，发送消息
        if order.WeChatUser != "" {
            weChatUsers := strings.Split(order.WeChatUser, ",")
            for _, user := range weChatUsers {
                userName, err := findUserNameByNickName(user)
                if err != nil {
                    fmt.Printf("查找用户 %s 失败: %v\n", user, err)
                    continue
                }
                
                messageContent := "哥，老板重新更换车队了，发#结账，可以结账记录,请尽快"
                sendTextMessage(messageContent, userName)
                if err != nil {
                    fmt.Printf("发送消息给用户 %s 失败: %v\n", user, err)
                }
            }
        }
        
        // 生成新的订单内容
        newContent := generateNewContent(order.Msg, requestData.Ranks, requestData.Stars, order.OrderType)
        
        if order.GroupName == "代发" {
            createBridge(order.GroupID, "代发", "@@本人", newContent, order.OrderType, 0)
        } else {
            createBridge("网站", "网站", order.GroupUserNickName, newContent, order.OrderType, 0)
        }
        
        // 将订单原始消息和新内容添加到globalGameIDMap
        globalGameIDMap[newContent] = orderDataBossId
        
        // 根据订单类型和内外部接单状态发送消息
        content := newContent
        switch order.OrderType {
        case "车队":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupswaibu(db, content)
            }
        case "陪玩":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupspeiwan(db, content)
            }
        case "小姐姐":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupsxjj(db, content)
            }
        case "代练":
            if isInternalOrderMode {
                forwardMessageToAllGroupsneibu(db, content)
            } else {
                forwardMessageToAllGroupsdailian(db, content)
            }
        }
        
        // 否则尝试查找新创建的订单ID
        newBridge, err := findBridgeForContent(newContent)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查找新订单失败", "message": "更换成功但无法获取新订单ID"})
            return
        }
        
        if newBridge == nil {
            // 尝试通过groupID和nickName查找
            var bridgeType string
            var nickName string
            if order.GroupName == "代发" {
                bridgeType = "代发"
                nickName = "@@本人"
            } else {
                bridgeType = "网站"
                nickName = order.GroupUserNickName
            }
            
            newBridge, err = findBridgeFromDB(bridgeType, nickName)
            if err != nil {
                c.JSON(http.StatusOK, gin.H{"message": "更换成功", "warning": "无法获取新订单ID"})
                return
            }
        }
        
        // 返回成功信息和新订单ID
        c.JSON(http.StatusOK, gin.H{
            "message": "更换成功",
            "newOrderId": newBridge.ID,
        })
    })
    
    r.POST("/quick-order", func(c *gin.Context) {
        var requestData struct {
            OrderId  string `json:"orderId"`
            Username string `json:"username"`
        }
    
        if err := c.BindJSON(&requestData); err != nil {
            fmt.Printf("Error binding JSON: %v\n", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
            return
        }
    
        if requestData.OrderId == "" {
            var groupName string
            var groupUserNickName string
        
            // 尝试从 Bridges 表中获取 GroupName
            err := db.QueryRow("SELECT GroupName FROM Bridges WHERE GroupUserNickName = ?", requestData.Username).Scan(&groupName)
            if err == nil {
                groupUserNickName = requestData.Username
            } else if err == sql.ErrNoRows {
                // 如果没有找到记录，则从 users 表中获取 name
                var name string
                err = db.QueryRow("SELECT name FROM users WHERE username = ?", requestData.Username).Scan(&name)
                if err != nil {
                    if err == sql.ErrNoRows {
                        c.JSON(http.StatusNotFound, gin.H{"error": "没有找到用户"})
                        return
                    }
                    fmt.Printf("Error querying user name: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户名失败", "details": err.Error()})
                    return
                }
                groupUserNickName = name
            } else {
                fmt.Printf("Error querying group name: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户组失败", "details": err.Error()})
                return
            }
        
            // 查询最新订单ID
            var latestOrderId string
            err = db.QueryRow("SELECT ID FROM Bridges WHERE GroupUserNickName = ? AND GameID != '' ORDER BY CreatedAt DESC LIMIT 1", groupUserNickName).Scan(&latestOrderId)
            if err != nil {
                if err == sql.ErrNoRows {
                    c.JSON(http.StatusNotFound, gin.H{"error": "没有找到最新的订单"})
                    return
                }
                fmt.Printf("Error querying latest order ID: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询最新订单ID失败", "details": err.Error()})
                return
            }
        
            requestData.OrderId = latestOrderId
        }            
    
        fmt.Printf("Request data: %+v\n", requestData)
    
        var order struct {
            Msg       string
            OrderType string
            FinalRank string
            GameID    string
        }
    
        // 查询订单信息
        err := db.QueryRow("SELECT Msg, OrderType, FinalRank, GameID FROM Bridges WHERE ID = ?", requestData.OrderId).Scan(&order.Msg, &order.OrderType, &order.FinalRank, &order.GameID)
        if err != nil {
            fmt.Printf("Error querying order: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询订单失败", "details": err.Error()})
            return
        }
    
        // 检查 GameID 是否为空
        if order.GameID == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "订单的GameID为空"})
            return
        }
    
        fmt.Printf("Order data: %+v\n", order)
    
        // 查询用户的AI群和名称信息
        var aiGroup, name string
        var starCount int
        err = db.QueryRow("SELECT ai_group, name, star_journal FROM users WHERE username = ?", requestData.Username).Scan(&aiGroup, &name, &starCount)
        if err != nil {
            fmt.Printf("Error querying AI group and name: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询AI群组失败", "details": err.Error()})
            return
        }
    
        fmt.Printf("User data: aiGroup=%s, name=%s, starCount=%d\n", aiGroup, name, starCount)
    
        // 更新用户的星卷数量
        if aiGroup == "" {
            _, err = db.Exec("UPDATE users SET star_journal = 0 WHERE username = ?", requestData.Username)
            if err != nil {
                fmt.Printf("Error updating stars for user: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                return
            }
        } else {
            // 获取现有星卷数量
            var existingStars int
            err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE UserName = ? AND GroupID = ?", name, aiGroup).Scan(&existingStars)
            if err != nil && err != sql.ErrNoRows {
                fmt.Printf("Error querying existing stars: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询现有星卷失败", "details": err.Error()})
                return
            }
    
            fmt.Printf("Existing stars: %d\n", existingStars)
    
            // 更新星卷数量
            _, err = db.Exec("UPDATE member_stars SET StarsCount = 0 WHERE UserName = ? AND GroupID = ?", name, aiGroup)
            if err != nil {
                fmt.Printf("Error updating stars for AI group: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                return
            }
            starCount = existingStars
        }
    
        fmt.Printf("Star count after update: %d\n", starCount)
    
        contactInfo := ""
        reContact := regexp.MustCompile(`(微信|QQ)`)
        matchContact := reContact.FindStringSubmatch(order.Msg)
        if len(matchContact) > 1 {
            contactInfo = matchContact[1]
        }
    
        positionInfo := ""
        rePosition := regexp.MustCompile(`(野|边|中|射|辅)`)
        matchPosition := rePosition.FindStringSubmatch(order.Msg)
        if len(matchPosition) > 1 {
            positionInfo = matchPosition[1]
        }
    
        fmt.Printf("Contact info: %s, Position info: %s\n", contactInfo, positionInfo)
    
        ranksAndPrices, _ := getRanksAndPrices(db)
    
        // 对ranksAndPrices按照段位长度进行排序
        var ranks []string
        for rank := range ranksAndPrices {
            ranks = append(ranks, rank)
        }
        sort.Slice(ranks, func(i, j int) bool {
            return len(ranks[i]) > len(ranks[j])
        })
    
        var matchedRanks []string
        input := order.FinalRank
        totalPrice := 0
        for _, rank := range ranks {
            rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
            for i := 0; i < rankOccurrences; i++ {
                matchedRanks = append(matchedRanks, rank)
                totalPrice += ranksAndPrices[rank]
                input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
            }
        }
        fmt.Printf("Matched ranks: %v, Total price: %d\n", matchedRanks, totalPrice)
    
        maxUpgrades, _, _, err := calculateMaxRank(db, starCount, matchedRanks, order.OrderType)
        if err != nil {
            fmt.Printf("Error calculating max rank: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "计算最大段位失败", "details": err.Error()})
            return
        }
    
        fmt.Printf("Max upgrades: %d\n", maxUpgrades)
    
        if maxUpgrades == 0 {
            fmt.Printf("Max upgrades is zero, returning\n")
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户没有足够的星卷"})
            return
        }
    
        // 如果匹配到多个段位，则应用多人优惠
        if len(matchedRanks) > 1 {
            totalPrice -= 1
        }
    
        content := contactInfo + positionInfo
        if len(matchedRanks) > 0 {
            content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + strconv.Itoa(totalPrice)
        } else {
            content += "，群价"
        }
        content += ",最多打" + strconv.Itoa(maxUpgrades) + "净胜"
        content += "，复制信息发我，#秒开车队来"
    
        globalGameIDMap[content] = order.GameID
    
        fmt.Printf("Generated content: %s\n", content)
    
        forwardMessageToAllGroupswaibu(db, content)
        createBridge("网站", "网站", requestData.Username, content, order.GameID, starCount)
    
        fmt.Printf("Bridge created with content: %s\n", content)
    
        // 示例响应
        c.JSON(http.StatusOK, gin.H{"success": true, "message": "操作成功"})
    })
    
    r.POST("/submitMessage", func(c *gin.Context) {
        var message struct {
            Username   string `json:"username"`
            Content    string `json:"content"`
            AvatarPath string `json:"avatar_path"`
        }
    
        if err := c.ShouldBindJSON(&message); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
            return
        }
    
        _, err := db.Exec("INSERT INTO message_board (username, content, avatar_path) VALUES (?, ?, ?)", message.Username, message.Content, message.AvatarPath)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save message"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"success": true})
    })
    r.POST("/favorites", func(c *gin.Context) {
        type FavoriteRequest struct {
            Username   string `json:"username"`
            PlaymateID string `json:"playmateID"`
            Liked      bool   `json:"liked"`
        }
        var req FavoriteRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        var err error
        if req.Liked {
            query := `INSERT INTO Favorites (Username, PlaymateID) VALUES (?, ?) ON CONFLICT(Username, PlaymateID) DO NOTHING`
            _, err = db.Exec(query, req.Username, req.PlaymateID)
        } else {
            query := `DELETE FROM Favorites WHERE Username = ? AND PlaymateID = ?`
            _, err = db.Exec(query, req.Username, req.PlaymateID)
        }

        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": true})
    })

    r.POST("/exit_order", func(c *gin.Context) {
        var requestData struct {
            OrderID string `json:"orderId"`
        }
        
        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无法解析请求"})
            return
        }
        
        // 获取订单信息，包括WeChatUser和GroupUserNickName
        var order struct {
            WeChatUser        string
            GroupUserNickName string // 添加GroupUserNickName字段
        }
        err := db.QueryRow("SELECT WeChatUser, GroupUserNickName FROM Bridges WHERE ID = ?", requestData.OrderID).Scan(
            &order.WeChatUser, &order.GroupUserNickName)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单信息失败"})
            return
        }
        
        // 将 IsActive 设置为 0
        _, err = db.Exec("UPDATE Bridges SET IsActive = 0 WHERE ID = ?", requestData.OrderID)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新订单失败"})
            return
        }
        
        if order.WeChatUser != "" {
            // 循环处理每一个 WeChatUser，发送消息
            weChatUsers := strings.Split(order.WeChatUser, ",")
            for _, user := range weChatUsers {
                userName, err := findUserNameByNickName(user)
                if err != nil {
                    fmt.Printf("查找用户 %s 失败: %v\n", user, err)
                    continue
                }
                
                messageContent := "老板已经下车了，哥，你发送#结账，根据提示结账，请尽快"
                sendTextMessage(messageContent, userName)
                if err != nil {
                    fmt.Printf("发送消息给用户 %s 失败: %v\n", user, err)
                }
            }
        } else {
            // 如果 WeChatUser 为空，归还星卷
            var starCost int
            err = db.QueryRow("SELECT StarCost FROM StarFreeze WHERE ID = ?", requestData.OrderID).Scan(&starCost)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询冻结星卷失败"})
                return
            }
            
            // 从 StarFreeze 表中删除该订单的记录
            _, err = db.Exec("DELETE FROM StarFreeze WHERE ID = ?", requestData.OrderID)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "删除冻结星卷记录失败"})
                return
            }
            
            // 使用订单的GroupUserNickName作为username
            username := order.GroupUserNickName
            
            // 归还星卷给用户
            var aiGroup, name string
            err = db.QueryRow("SELECT ai_group, name FROM users WHERE username = ?", username).Scan(&aiGroup, &name)
            if err != nil {
                fmt.Printf("Error querying AI group: %v\n", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询AI群组失败", "details": err.Error()})
                return
            }
            
            if aiGroup == "" {
                _, err = db.Exec("UPDATE users SET star_journal = star_journal + ? WHERE username = ?", starCost, username)
                if err != nil {
                    fmt.Printf("Error updating stars for user: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                    return
                }
            } else {
                _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount + ? WHERE UserName = ? AND GroupID = ?", starCost, name, aiGroup)
                if err != nil {
                    fmt.Printf("Error updating stars for AI group: %v\n", err)
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "更新星卷失败", "details": err.Error()})
                    return
                }
            }
        }
        
        // 关闭WebSocket连接
        closeOrderWebSockets(requestData.OrderID)
        
        c.JSON(http.StatusOK, gin.H{"message": "退出成功"})
    })
    // 打手页面
    r.GET("/hitt/:order_id", CheckOrderExist(), func(c *gin.Context) {
        orderID := c.Param("order_id")
    
        // 查询订单信息
        var order struct {
            Msg    string
            GameID string
        }
        err := db.QueryRow("SELECT Msg FROM Bridges WHERE ID = ?", orderID).Scan(&order.Msg)
        if err != nil {
            if err == sql.ErrNoRows {
                c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
            } else {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单信息失败"})
            }
            return
        }
    
        // 提取开始段位逻辑
        startRanks := "不存在"
        if order.Msg != "" {
            // 获取所有段位信息
            ranksCosts, err := getAllRanksAndCosts(db)
            if err == nil {
                // 解析巅峰段位
                matchedPeak, _ := parsePeakRank(order.Msg)
                var matchedOrders []string  // 改为存储字符串

                msgCopy := order.Msg
                if matchedPeak != "" {
                    // 获取巅峰段位的下标
                    if order, err := getAdjustedRankOrder(matchedPeak, db); err == nil {
                        matchedOrders = append(matchedOrders, strconv.Itoa(order))
                    }
                } else {
                    // 按段位名称长度降序排序
                    sort.Slice(ranksCosts, func(i, j int) bool {
                        return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                    })

                    // 提取匹配段位
                    for _, rankCost := range ranksCosts {
                        rank := rankCost[0]
                        for strings.Contains(msgCopy, rank) {
                            // 获取调整后的下标并转为字符串
                            if adjustedOrder, err := getAdjustedRankOrder(rank, db); err == nil {
                                matchedOrders = append(matchedOrders, strconv.Itoa(adjustedOrder+332))
                                msgCopy = strings.Replace(msgCopy, rank, "", 1)
                            }
                        }
                    }
                }

                if len(matchedOrders) > 0 {
                    startRanks = strings.Join(matchedOrders, " + ")
                }
            }
        }
        
        rankQuery := "SELECT Rank, Price, StarCost, RankOrder FROM RankPrices WHERE RankOrder BETWEEN 333 AND 498 OR RankOrder >= 499"
        rankRows, err := db.Query(rankQuery)
        if err != nil && err != sql.ErrNoRows {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取段位价格失败"})
            return
        }
        defer rankRows.Close()
    
        var ranks []map[string]interface{}
        for rankRows.Next() {
            var rank string
            var price, starCost, rankOrder int
            if err := rankRows.Scan(&rank, &price, &starCost, &rankOrder); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "解析段位数据失败"})
                return
            }
    
            encryptedPrice := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%d", price)))
            ranks = append(ranks, map[string]interface{}{
                "Rank":      rank,
                "Price":     encryptedPrice,
                "StarCost":  starCost,
                "RankOrder": rankOrder,
            })
        }
    
        ranksJSON, err := json.Marshal(ranks)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "序列化段位数据失败"})
            return
        }
    
        c.HTML(http.StatusOK, "hitter.html", gin.H{
            "OrderID":         orderID,
            "ranks":          template.JS(ranksJSON),
            "StartRanks":     startRanks,
            "Role":    "hitter",
        })
    })

    // 重定向原有的boss路由到pipei路由
    r.GET("/boss/:order_id", func(c *gin.Context) {
        orderID := c.Param("order_id")
        
        // 查询数据库检查是否已匹配
        var wechatUser string
        isMatched := false
        
        err := db.QueryRow("SELECT WeChatUser FROM Bridges WHERE ID = ?", orderID).Scan(&wechatUser)
        if err == nil && wechatUser != "" {
            isMatched = true
        }
        
        // 渲染模板并传递参数
        c.HTML(http.StatusOK, "pipei.html", gin.H{
            "OrderID": orderID,
            "VipQuery": c.Query("vip"),
            "CrowdStatus": previousWindowState, // 传递之前保存的状态
            "IsMatched": isMatched,             // 是否已经匹配成功
        })
    })
    // 新建pipei路由，包含原有boss路由的所有逻辑，但仍然使用boss.html模板
    r.GET("/pipei/:order_id", func(c *gin.Context) {
        orderID := c.Param("order_id")

        // 查询订单信息
        var order struct {
            Msg    string
            GameID string
        }
        err := db.QueryRow("SELECT Msg FROM Bridges WHERE ID = ?", orderID).Scan(&order.Msg)
        if err != nil {
            if err == sql.ErrNoRows {
                c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
            } else {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单信息失败"})
            }
            return
        }

        // 提取开始段位逻辑
        startRanks := "不存在"
        if order.Msg != "" {
            // 获取所有段位信息
            ranksCosts, err := getAllRanksAndCosts(db)
            if err == nil {
                // 解析巅峰段位
                matchedPeak, _ := parsePeakRank(order.Msg)
                var matchedOrders []string  // 改为存储字符串

                msgCopy := order.Msg
                if matchedPeak != "" {
                    // 获取巅峰段位的下标
                    if order, err := getAdjustedRankOrder(matchedPeak, db); err == nil {
                        matchedOrders = append(matchedOrders, strconv.Itoa(order))
                    }
                } else {
                    // 按段位名称长度降序排序
                    sort.Slice(ranksCosts, func(i, j int) bool {
                        return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                    })

                    // 提取匹配段位
                    for _, rankCost := range ranksCosts {
                        rank := rankCost[0]
                        for strings.Contains(msgCopy, rank) {
                            // 获取调整后的下标并转为字符串
                            if adjustedOrder, err := getAdjustedRankOrder(rank, db); err == nil {
                                matchedOrders = append(matchedOrders, strconv.Itoa(adjustedOrder+332))
                                msgCopy = strings.Replace(msgCopy, rank, "", 1)
                            }
                        }
                    }
                }

                if len(matchedOrders) > 0 {
                    startRanks = strings.Join(matchedOrders, " + ")
                }
            }
        }

        // 查询可更换状态和段位价格
        canChangeGroup := c.Query("vip") != ""
        
        rankQuery := "SELECT Rank, Price, StarCost, RankOrder FROM RankPrices WHERE RankOrder BETWEEN 333 AND 498 OR RankOrder >= 499"
        rankRows, err := db.Query(rankQuery)
        if err != nil && err != sql.ErrNoRows {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取段位价格失败"})
            return
        }
        defer rankRows.Close()

        var ranks []map[string]interface{}
        for rankRows.Next() {
            var rank string
            var price, starCost, rankOrder int
            if err := rankRows.Scan(&rank, &price, &starCost, &rankOrder); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "解析段位数据失败"})
                return
            }

            encryptedPrice := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%d", price)))
            ranks = append(ranks, map[string]interface{}{
                "Rank":      rank,
                "Price":     encryptedPrice,
                "StarCost":  starCost,
                "RankOrder": rankOrder,
            })
        }

        ranksJSON, err := json.Marshal(ranks)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "序列化段位数据失败"})
            return
        }

        // 仍然使用boss.html模板渲染页面
        c.HTML(http.StatusOK, "boss.html", gin.H{
            "OrderID":         orderID,
            "Role":           "boss",
            "ranks":          template.JS(ranksJSON),
            "CanChangeGroup": canChangeGroup,
            "StartRanks":     startRanks,
            "IsRedirected":   c.Query("redirected") == "true", // 传递重定向标志
        })
    })
   // 添加轮询接口，检查是否匹配成功
    r.GET("/api/check-match/:order_id", func(c *gin.Context) {
        orderID := c.Param("order_id")
        
        // 查询数据库检查是否已匹配
        var wechatUser string
        isMatched := false
        
        err := db.QueryRow("SELECT WeChatUser FROM Bridges WHERE ID = ?", orderID).Scan(&wechatUser)
        if err == nil && wechatUser != "" {
            isMatched = true
        }
        
        c.JSON(http.StatusOK, gin.H{
            "isMatched": isMatched,
            "status": previousWindowState,
        })
    })
    // 添加检查订单状态的API端点
    r.GET("/api/check-order-status/:order_id", func(c *gin.Context) {
        orderID := c.Param("order_id")
        if orderID == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "订单ID不能为空"})
            return
        }
        
        // 获取角色参数
        role := c.Query("role")
        if role == "" {
            role = "boss" // 默认为boss角色
        }

        // 首先获取订单状态和用户昵称
        var isActive bool // 修改为bool类型以匹配数据库
        var groupUserNickName string
        
        // 使用更安全的错误处理方式
        err := db.QueryRow(`
            SELECT IsActive, GroupUserNickName
            FROM Bridges WHERE ID = ?
        `, orderID).Scan(&isActive, &groupUserNickName)

        if err != nil {
            if err == sql.ErrNoRows {
                // 订单不存在时，返回没有找到的信息
                c.JSON(http.StatusOK, gin.H{
                    "orderID": orderID,
                    "isActive": false,
                    "error": "订单不存在",
                })
            } else {
                // 打印详细错误信息用于调试
                log.Printf("获取订单状态失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "获取订单状态失败"})
            }
            return
        }

        // 只有在是boss角色且订单非活跃时才查找新订单
        var newOrderID string
        if role == "boss" && !isActive && groupUserNickName != "" { // 修改条件判断，使用!isActive而不是isActive == 0
            // 使用更安全的错误处理方式
            err := db.QueryRow(`
                SELECT ID FROM Bridges 
                WHERE GroupID = ? AND GroupUserNickName = ? AND IsActive = 1 
                ORDER BY CreatedAt DESC LIMIT 1
            `, "网站", groupUserNickName).Scan(&newOrderID)

            // 正确处理"没有找到记录"的情况
            if err != nil && err != sql.ErrNoRows {
                log.Printf("查询替代订单失败: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询替代订单失败"})
                return
            }
            // 如果是sql.ErrNoRows，newOrderID将保持为空字符串
        }

        // 返回订单状态和可能的重定向目标
        response := gin.H{
            "orderID": orderID,
            "isActive": isActive, // 直接使用布尔值
        }
        
        // 只有boss角色才返回重定向信息
        if role == "boss" {
            response["redirectTo"] = newOrderID
        } else {
            response["message"] = "打手不需要重定向"
        }
        
        c.JSON(http.StatusOK, response)
    })
    r.GET("/ws/:order_id", CheckOrderExist(), CheckOrderRedirect(), RateLimitMiddleware(), func(c *gin.Context) {
        orderID := c.Param("order_id")
        role := strings.ToLower(c.Query("role"))
        
        // 检查是否跳过历史消息
        skipHistory := c.Query("skipHistory") == "true"
        
        // 验证角色参数
        if role != "hitter" && role != "boss" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无效的角色参数"})
            return
        }
        
        // 升级WebSocket连接
        conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
        if err != nil {
            c.Error(fmt.Errorf("WebSocket升级失败: %w", err))
            return
        }
        defer conn.Close()
        
        // 创建客户端记录
        client := Client{
            conn:     conn,
            role:     role,
            username: generateAnonymousID(), // 生成匿名标识
        }
        
        // 注册连接
        clientsMutex.Lock()
        if clients[orderID] == nil {
            clients[orderID] = make(map[*websocket.Conn]Client)
        }
        clients[orderID][conn] = client
        clientsMutex.Unlock()
        
        // 发送历史消息，只有在不跳过历史时才发送
        if !skipHistory {
            sendHistoryMessages(orderID, conn)
        }
        
        // 连接关闭时清理
        defer func() {
            clientsMutex.Lock()
            delete(clients[orderID], conn)
            if len(clients[orderID]) == 0 {
                delete(clients, orderID)
            }
            clientsMutex.Unlock()
        }()
        
        // 消息处理循环
        for {
            _, message, err := conn.ReadMessage()
            if err != nil {
                break
            }
            parsedMsg, _ := parseMessageContent(message)
            
            // 保存消息到数据库
            saveMessageToDB(orderID, client.role, parsedMsg)
            
            // 广播消息给所有连接
            broadcastMessage(orderID, client.role, parsedMsg, conn)
            
            // 微信消息处理
            handleWeChatNotification(orderID, parsedMsg, client.role)
        }
    })
    r.GET("/api/boss-messages/:order_id", func(c *gin.Context) {
        // 获取订单ID
        orderID := c.Param("order_id")
        if orderID == "" {
            c.JSON(http.StatusBadRequest, gin.H{
                "success": false,
                "error": "缺少订单ID",
            })
            return
        }
    
        // 查询数据库中该订单的所有老板消息
        rows, err := db.Query(`
            SELECT Message 
            FROM BridgeMessages 
            WHERE BridgeID = ? AND (Role = 'boss' OR Role = '老板')
            ORDER BY Timestamp DESC
        `, orderID)
        
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "success": false,
                "error": "数据库查询错误",
            })
            return
        }
        defer rows.Close()
    
        // 收集所有消息
        messages := []string{}
        for rows.Next() {
            var message string
            if err := rows.Scan(&message); err != nil {
                continue
            }
            messages = append(messages, message)
        }
    
        // 返回JSON响应
        c.JSON(http.StatusOK, gin.H{
            "success": true,
            "messages": messages,
        })
    })
    // ========= /api/withdraw/auditors =========
    r.POST("/api/withdraw/auditors", func(c *gin.Context) {
        /* ---------- 0. 取 code（支持 JSON / form / query） ---------- */
        code := c.PostForm("code")
        if code == "" {
            var body struct{ Code string `json:"code"` }
            _ = c.ShouldBindJSON(&body)
            if body.Code != "" {
                code = body.Code
            } else {
                code = c.Query("code")
            }
        }
        log.Printf("[auditors] 收到 code=%s", code)

        if code == "" {
            c.JSON(http.StatusBadRequest, gin.H{"code": 1, "message": "缺少 code"})
            return
        }

        /* ---------- 1. code → openid ---------- */
        if _, err := getOpenIDFromCode(code); err != nil {
            log.Printf("[auditors] getOpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "message": "code 无效"})
            return
        }

        /* ---------- 2. 审核员列表（示例静态） ---------- */
        list := []gin.H{
            {
                "id":        1,
                "nickname":  "国1车队联系员-梦奇（24h 在）",
                "avatarUrl": "https://wx.qlogo.cn/mmhead/ver_1/WTyQvWoF15LXp6Irnpiaic5RQQfJmnn5GsnYWm2bcjNeNZfl4xVicHjMOWvFDlMfFbo3ibdUibvusRialicWTeZLmphdcgG6H2xcibx23kYkSjnzrEo/0",
                "description": "提现会收 2 元服务费，48h 内结算",
            },
        }
        log.Printf("[auditors] 返回 %d 条审核员", len(list))
        c.JSON(http.StatusOK, gin.H{"code": 0, "data": list})
    })

    // ========= /api/user/last-qr =========
    r.POST("/api/user/last-qr", func(c *gin.Context) {
        /* ---------- 0. 取 code ---------- */
        code := c.PostForm("code")
        if code == "" {
            var body struct{ Code string `json:"code"` }
            _ = c.ShouldBindJSON(&body)
            if body.Code != "" {
                code = body.Code
            } else {
                code = c.Query("code")
            }
        }
        log.Printf("[lastQR] 收到 code=%s", code)

        if code == "" {
            c.JSON(http.StatusBadRequest, gin.H{"code": 1, "message": "缺少 code"})
            return
        }

        /* ---------- 1. code → openid ---------- */
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[lastQR] getOpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "message": "获取 openid 失败"})
            return
        }
        log.Printf("[lastQR] openid=%s", openid)

        /* ---------- 2. users 表拿 wechatname ---------- */
        var wechatName string
        err = db.QueryRow(`SELECT wechatname FROM users WHERE openid = ?`, openid).
            Scan(&wechatName)
        if err == sql.ErrNoRows || wechatName == "" {
            log.Printf("[lastQR] 未绑定 wechatname")
            c.JSON(http.StatusOK, gin.H{"code": 3, "message": "未绑定接单微信昵称"})
            return
        }
        if err != nil {
            log.Printf("[lastQR] 查询 users 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "服务器查询错误"})
            return
        }
        log.Printf("[lastQR] wechatname=%s", wechatName)

        /* ---------- 3. friends 表拿 nickName ---------- */
        var nickName string
        err = db.QueryRow(`SELECT nickName FROM friends WHERE userName = ?`, wechatName).
            Scan(&nickName)
        if err == sql.ErrNoRows || nickName == "" {
            log.Printf("[lastQR] friends 表无 nickName")
            c.JSON(http.StatusOK, gin.H{"code": 4, "message": "好友昵称不存在，请先保存二维码"})
            return
        }
        if err != nil {
            log.Printf("[lastQR] 查询 friends 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "服务器查询错误"})
            return
        }
        log.Printf("[lastQR] nickName=%s", nickName)

        /* ---------- 4. 本地文件检测 ---------- */
        imageDir := "/root/wechat/image"
        pattern  := filepath.Join(imageDir, fmt.Sprintf("%s_收款码.jpg", nickName))
        matches, _ := filepath.Glob(pattern)
        log.Printf("[lastQR] 匹配到 %d 张收款码", len(matches))

        switch len(matches) {
        case 0:
            c.JSON(http.StatusOK, gin.H{"code": 5, "message": "未上传收款码"})
        case 1:
            file := filepath.Base(matches[0])
            url  := "https://www.moki-flanke.icu/image/" + file
            c.JSON(http.StatusOK, gin.H{"code": 0, "url": url})
        default:
            c.JSON(http.StatusOK, gin.H{"code": 6, "message": "检测到多张收款码，请选择人工提现"})
        }
    })
    // ========= /api/upload/qr =========
    r.POST("/api/upload/qr", func(c *gin.Context) {
        code := c.PostForm("code")
        if code == "" {                       // 前端理论上一定带 code，保险起见再兜底
            c.JSON(http.StatusBadRequest, gin.H{"code": 1, "message": "缺少 code"})
            return
        }

        /* ---------- 1. code → openid ---------- */
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[uploadQR] getOpenID 失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "message": "code 无效"})
            return
        }

        /* ---------- 2. openid → wechatname (users) ---------- */
        var wechatName string
        err = db.QueryRow(`SELECT wechatname FROM users WHERE openid = ?`, openid).Scan(&wechatName)
        if err == sql.ErrNoRows || wechatName == "" {
            c.JSON(http.StatusOK, gin.H{"code": 3, "message": "未绑定接单微信昵称"})
            return
        }
        if err != nil {
            log.Printf("[uploadQR] 查询 users 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "服务器错误"})
            return
        }

        /* ---------- 3. wechatname → nickName (friends) ---------- */
        var nickName string
        err = db.QueryRow(`SELECT nickName FROM friends WHERE userName = ?`, wechatName).Scan(&nickName)
        if err == sql.ErrNoRows || nickName == "" {
            c.JSON(http.StatusOK, gin.H{"code": 4, "message": "好友昵称不存在，请先保存二维码"})
            return
        }
        if err != nil {
            log.Printf("[uploadQR] 查询 friends 出错: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "服务器错误"})
            return
        }

        /* ---------- 4. 获取上传文件 ---------- */
        fileHeader, err := c.FormFile("file")
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"code": 5, "message": "缺少文件"})
            return
        }

        /* ---------- 5. 生成目标文件名：<nickName>_收款码.jpg ---------- */
        saveDir := "/root/wechat/image"
        filename := fmt.Sprintf("%s_收款码.jpg", nickName)
        fullPath := filepath.Join(saveDir, filename)

        // 保存 (存在则覆盖)
        if err := c.SaveUploadedFile(fileHeader, fullPath); err != nil {
            log.Printf("[uploadQR] 保存失败: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 6, "message": "保存失败"})
            return
        }

        /* ---------- 6. 返回静态 URL ---------- */
        url := "https://www.moki-flanke.icu/image/" + filename
        log.Printf("[uploadQR] 上传完成 -> %s", url)

        c.JSON(http.StatusOK, gin.H{
            "code": 0,
            "url":  url,
        })
    })
    // ========= 提现申请（写入 WithdrawAudit） =========
    r.POST("/api/withdraw/apply", func(c *gin.Context) {
        var req struct {
            Code      string  `form:"code"      json:"code"`
            Amount    float64 `form:"amount"    json:"amount"`
            AuditorId int64   `form:"auditorId" json:"auditorId"`
            QrUrl     string  `form:"qrUrl"     json:"qrUrl"`
        }
        if err := c.ShouldBind(&req); err != nil ||
            req.Code == "" || req.Amount <= 0 || req.QrUrl == "" {
            c.JSON(400, gin.H{"code": 1, "message": "参数错误"})
            return
        }

        /* ---------- 1. code → openid ---------- */
        openid, err := getOpenIDFromCode(req.Code)
        if err != nil {
            c.JSON(500, gin.H{"code": 2, "message": "code 无效"})
            return
        }

        /* ---------- 2. wechatname & 余额 ---------- */
        var wechatName string
        var balance    float64
        err = db.QueryRow(`SELECT wechatname, balance FROM users WHERE openid = ?`, openid).
                Scan(&wechatName, &balance)
        if err != nil || wechatName == "" {
            c.JSON(200, gin.H{"code": 3, "message": "用户信息缺失 / 未绑定微信昵称"})
            return
        }
        if balance < req.Amount {
            c.JSON(200, gin.H{"code": 4, "message": "余额不足"})
            return
        }

        /* ---------- 3. 事务 ---------- */
        tx, _ := db.Begin()
        defer tx.Rollback()

        // 3-1 扣余额
        if _, err := tx.Exec(`UPDATE users SET balance = balance - ? WHERE openid = ?`,
            req.Amount, openid); err != nil {
            c.JSON(500, gin.H{"code": 5, "message": "扣款失败"}); return
        }

        // 3-2 写 WithdrawAudit
        wid := uuid.New().String()
        if _, err := tx.Exec(`
            INSERT INTO WithdrawAudit
                (id, openid, wechatname, qr_url, amount, status, auditor_id, create_at, update_at)
            VALUES (?, ?, ?, ?, ?, 'pending', ?, datetime('now'), datetime('now'))`,
            wid, openid, wechatName, req.QrUrl, req.Amount, req.AuditorId); err != nil {
            c.JSON(500, gin.H{"code": 6, "message": "保存审核记录失败"}); return
        }
        /* ---------- 3-3  写用户流水 ---------- */
        if _, err := tx.Exec(`
            INSERT INTO UserTransactions
                (ID, OpenID, TransactionType, Amount, ActualAmount, Status, CreateTime)
            VALUES (?, ?, '提现', ?, ?, 'success', datetime('now'))`,
            uuid.New().String(),           // ID
            openid,                        // OpenID
            -req.Amount,                   // Amount  (负数)
            -req.Amount);                  // ActualAmount 同样负数
        err != nil {

            // ⚠️ 记录详细日志
            log.Printf("[withdraw/apply] 写流水失败 openid=%s amount=%.2f err=%v",
                openid, req.Amount, err)

            tx.Rollback()
            c.JSON(500, gin.H{
                "code":    7,
                "message": "写流水失败，请稍后再试",
            })
            return
        }

        tx.Commit()

        /* ---------- 4. 同步通知审核员（仅示例编号 1） ---------- */
        if req.AuditorId == 1 {
            go func(aid int64, wid, wname string, amt float64) {
                msg := fmt.Sprintf(
                    "【提现申请】\n昵称:%s\n金额: %.2f 元\n网址: https://www.moki-flanke.icu/withdrawal/manage?auditorId=%d\n记录ID:%s",
                    wname, amt, aid, wid)

            sendTextMessage(msg, "moki-flanke")
           }(req.AuditorId, wid, wechatName, req.Amount)
        }

        c.JSON(200, gin.H{"code": 0, "message": "提现已提交，等待审核"})
    })

    // ======== 1. GET /api/audit/withdrawals  按审核员拉待审核列表 ========
    r.GET("/api/audit/withdrawals", func(c *gin.Context) {
        auditorID := c.Query("auditorId")
        if auditorID == "" {
            c.JSON(http.StatusBadRequest, gin.H{"code": 1, "message": "缺少 auditorId"})
            return
        }

        q := `SELECT id, openid, qr_url, amount, status, create_at, auditor_id
                FROM WithdrawAudit
            WHERE auditor_id = ? AND status = 'pending'
            ORDER BY create_at DESC`

        rows, err := db.Query(q, auditorID)
        if err != nil {
            log.Printf("[withdrawals] query err: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "查询失败"})
            return
        }
        defer rows.Close()

        var list []Withdrawal
        for rows.Next() {
            var w Withdrawal
            if err := rows.Scan(&w.ID, &w.OpenID, &w.QRUrl,
                &w.Amount, &w.Status, &w.CreateAt, &w.AuditorID); err != nil {
                log.Printf("[withdrawals] scan err: %v", err)
                c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "解析失败"})
                return
            }
            list = append(list, w)
        }
        if err := rows.Err(); err != nil {
            log.Printf("[withdrawals] rows err: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"code": 99, "message": "遍历失败"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"code": 0, "data": list})
    })


   // ======== 2. POST /api/audit/withdrawals/:id/settle  结账 ========
    r.POST("/api/audit/withdrawals/:id/settle", func(c *gin.Context) {
        id := c.Param("id")

        /* ---------- ① 取待结账记录 ---------- */
        var w Withdrawal
        if err := db.QueryRow(`SELECT openid, amount FROM WithdrawAudit WHERE id=?`, id).
            Scan(&w.OpenID, &w.Amount); err != nil {

            if err == sql.ErrNoRows {
                c.JSON(404, gin.H{"code": 1, "message": "记录不存在"}); return
            }
            log.Printf("[settle] select err: %v", err)
            c.JSON(500, gin.H{"code": 99, "message": "查询失败"}); return
        }

        /* ---------- ② 事务 ---------- */
        tx, err := db.Begin()
        if err != nil {
            log.Printf("[settle] begin err: %v", err)
            c.JSON(500, gin.H{"code": 99, "message": "开启事务失败"}); return
        }

        // 2-1 更新审核状态
        if _, err = tx.Exec(`UPDATE WithdrawAudit
                            SET status='done', update_at=datetime('now')
                            WHERE id=?`, id); err != nil {
            log.Printf("[settle] update WithdrawAudit err: %v", err)
            tx.Rollback(); c.JSON(500, gin.H{"code": 2, "message": "更新失败"}); return
        }

        // 2-2 把对应 UserTransactions 由 pending → success
        if _, err = tx.Exec(`UPDATE UserTransactions
                            SET Status='success'
                            WHERE RelatedOrderID=? AND TransactionType='withdraw'`,
                            id); err != nil {
            log.Printf("[settle] update UserTransactions err: %v", err)
            tx.Rollback(); c.JSON(500, gin.H{"code": 3, "message": "流水更新失败"}); return
        }

        /* ---------- ③ 提交 ---------- */
        if err = tx.Commit(); err != nil {
            log.Printf("[settle] commit err: %v", err)
            c.JSON(500, gin.H{"code": 99, "message": "提交失败"}); return
        }
        log.Printf("[settle] 完成 id=%s openid=%s amount=%.2f", id, w.OpenID, w.Amount)

        accessToken, err := getMiniAccessToken()
        if err != nil {
            log.Printf("[subscribe] get token err: %v", err)
            c.JSON(200, gin.H{"code": 0, "message": "结账成功，但获取 token 失败"})
            return
        }
    
        // 1. 组装消息体 —— 字段名、类型与小程序后台模板保持一致
        data := map[string]interface{}{
            "thing1":   map[string]string{"value": "您的提现审核已通过"},           // thing1 ≤ 20 字
            "amount10": map[string]string{"value": fmt.Sprintf("%.2f元", w.Amount)}, // amount10 金额格式
            "thing12":  map[string]string{"value": "资金已转入二维码账户"},          // thing12 ≤ 20 字
        }
    
        subscribeMessage := map[string]interface{}{
            "touser":            w.OpenID,                                       // 收件人 openid
            "template_id":       "oVsXdWABrZ3XwL95iFlsyKlrK0ynuXhp26_GR3PBDNg", // 与后台保持一致
            "page":              "pages/order_list/order_list",
            "miniprogram_state": "formal",
            "lang":              "zh_CN",
            "data":              data,
        }
    
        if err := sendSubscribeMessage(accessToken, subscribeMessage); err != nil {
            log.Printf("[subscribe] send err: %v", err)
        } else {
            log.Printf("[subscribe] 已向 %s 推送提现通过通知", w.OpenID)
        }      

        c.JSON(http.StatusOK, gin.H{"code": 0})
    })

    // 添加充值管理页面的路由
    r.GET("/withdrawal/manage", func(c *gin.Context) {
        // 将当前接单状态传递到前端
        c.HTML(http.StatusOK, "withdrawal.html", gin.H{
        })
    })
    r.GET("/ws/balance", func(c *gin.Context) {
        code := c.Query("code")
        
        // 验证code是否存在
        if code == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "缺少微信登录code"})
            return
        }
        
        // 使用code获取openid
        log.Printf("[DEBUG] 开始获取OpenID，Code: %s", code)
        openid, err := getOpenIDFromCode(code)
        if err != nil {
            log.Printf("[ERROR] 获取OpenID失败: %v | Code: %s", err, code)
            c.JSON(http.StatusInternalServerError, gin.H{
                "code":    2,
                "message": "获取用户信息失败",
            })
            return
        }
        
        // 检查用户是否存在
        var exists bool
        err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE openid = ?)", openid).Scan(&exists)
        if err != nil || !exists {
            c.JSON(http.StatusBadRequest, gin.H{"error": "用户不存在"})
            return
        }
        
        // 升级WebSocket连接
        conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
        if err != nil {
            c.Error(fmt.Errorf("WebSocket升级失败: %w", err))
            return
        }
        defer conn.Close()
        
        // 注册连接
        balanceClientsMux.Lock()
        if balanceClients[openid] == nil {
            balanceClients[openid] = make(map[*websocket.Conn]bool)
        }
        balanceClients[openid][conn] = true
        balanceClientsMux.Unlock()
        
        // 连接建立后立即发送当前余额
        sendCurrentBalance(openid, conn)
        
        // 连接关闭时清理
        defer func() {
            balanceClientsMux.Lock()
            delete(balanceClients[openid], conn)
            if len(balanceClients[openid]) == 0 {
                delete(balanceClients, openid)
            }
            balanceClientsMux.Unlock()
        }()
        
        // 保持连接活跃的简单心跳
        for {
            _, _, err := conn.ReadMessage()
            if err != nil {
                break
            }
            // 这里只处理心跳，不需要其他逻辑
        }
    })
    r.POST("/api/checkout", func(c *gin.Context) {
		// 在路由处理函数内部定义结构体
		type CheckoutRequest struct {
			OrderID  string `json:"orderId" binding:"required"`
			BossName string `json:"bossName" binding:"required"`
			NetWin   int    `json:"netWin" binding:"required"`
			Price    int    `json:"price" binding:"required"`
		}

		var req CheckoutRequest

		// 解析请求体
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误: " + err.Error()})
			return
		}
        var wechatUser string
		query := `SELECT WeChatUser FROM Bridges WHERE ID = ?`
		
		err := db.QueryRow(query, req.OrderID).Scan(&wechatUser)
		if err != nil {
			if err == sql.ErrNoRows {
				c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在或已完成"})
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "查询订单信息失败: " + err.Error()})
			}
			return
		}
        var fromUserName string
		query = `SELECT userName FROM friends WHERE nickName = ?`
		
		err = db.QueryRow(query, wechatUser).Scan(&fromUserName)
		if err != nil {
			if err == sql.ErrNoRows {
				c.JSON(http.StatusNotFound, gin.H{"error": "未找到该老板名称对应的用户"})
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户信息失败: " + err.Error()})
			}
			return
		}
		// 构造消息内容 - 使用BossName作为gameID
		content := fmt.Sprintf("%s%d+%d", req.BossName, req.NetWin, req.Price)

		// 直接调用处理函数，无需检查错误返回
		processNumericResponse(content, fromUserName, wechatUser)

		// 返回成功响应
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"message": "结账成功",
			"data": gin.H{
				"orderId":      req.OrderID,
				"bossName":     req.BossName,
				"fromUserName": fromUserName,
				"netWin":       req.NetWin,
				"price":        req.Price,
			},
		})
	})
    r.POST("/api/wxacode/unlimited", generateQRCode)
    r.POST("/add-to-blacklist", addToBlacklist)
    r.POST("/send_message", sendMessage)
    r.GET("/blacklist", getBlacklist)
    // 添加路由
    r.POST("/remove-from-blacklist", removeFromBlacklist)
	// 启动监听 8080 端口
	r.Run(":8080")
}
// 取消拉黑API
func removeFromBlacklist(c *gin.Context) {
    var req struct {
        Nickname string `json:"nickname" binding:"required"`
        Code     string `json:"code" binding:"required"`
    }
    
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
        return
    }

    // 获取OpenID
    openid, err := getOpenIDFromCode(req.Code)
    if err != nil {
        log.Printf("[ERROR] 获取OpenID失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "success": false,
            "message": "获取用户信息失败",
        })
        return
    }

    // 从 friends 表中查询 userName，优先选择以 wxid 开头的
    var username string
    err = db.QueryRow(`
        SELECT userName 
        FROM friends 
        WHERE nickName = ? 
        ORDER BY 
            CASE 
                WHEN userName LIKE 'wxid%' THEN 0
                ELSE 1
            END,
            id ASC
        LIMIT 1
    `, req.Nickname).Scan(&username)
    
    if err != nil {
        log.Printf("[ERROR] 查询用户名失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "success": false,
            "message": "未找到对应用户",
        })
        return
    }

    // 将黑名单记录设置为非活动状态
    _, err = db.Exec("UPDATE blacklist SET is_active = 0 WHERE username = ? AND openid = ? AND is_active = 1", 
        username, openid)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "移出黑名单失败"})
        return
    }

    c.JSON(http.StatusOK, gin.H{"success": true, "message": "已成功移出黑名单"})
}
func sendMessage(c *gin.Context) {
    var req ReportRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
        return
    }
    
    // 更新用户举报状态
    _, err := db.Exec("UPDATE user_stats SET IsReported = 1 WHERE NickName = ?", req.Nickname)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "更新举报状态失败"})
        return
    }
    
    // 获取当前id为2的公告内容
    var currentMessage string
    err = db2.QueryRow("SELECT message FROM announcements WHERE id = 2").Scan(&currentMessage)
    if err != nil {
        if err == sql.ErrNoRows {
            // 如果id为2的记录不存在，创建一个新记录
            newMessage := "用户 " + req.Nickname + " 被举报，原因：" + req.Reason
            _, err = db2.Exec("INSERT INTO announcements (id, message) VALUES (2, ?)", newMessage)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "创建举报记录失败"})
                return
            }
        } else {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取公告记录失败"})
            return
        }
    } else {
        // 追加新的举报信息到现有记录
        newMessage := currentMessage + "\n" + "用户 " + req.Nickname + " 被举报，原因：" + req.Reason
        _, err = db2.Exec("UPDATE announcements SET message = ? WHERE id = 2", newMessage)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新举报记录失败"})
            return
        }
    }
    
    c.JSON(http.StatusOK, gin.H{"success": true, "message": "举报成功"})
}
// 发送当前余额
func sendCurrentBalance(openid string, conn *websocket.Conn) {
    var balance float64
    err := db.QueryRow("SELECT balance FROM users WHERE openid = ?", openid).Scan(&balance)
    if err != nil {
        log.Printf("[ERROR] 获取用户余额失败: %v | OpenID: %s", err, openid)
        return
    }
    
    message := map[string]interface{}{
        "type": "balance_update",
        "balance": fmt.Sprintf("%.2f", balance),
    }
    
    jsonMsg, err := json.Marshal(message)
    if err != nil {
        log.Printf("[ERROR] 序列化余额消息失败: %v", err)
        return
    }
    
    if err := conn.WriteMessage(websocket.TextMessage, jsonMsg); err != nil {
        log.Printf("[ERROR] 发送余额消息失败: %v", err)
    }
}

// 通知用户余额更新的函数，在余额变动后调用
func notifyBalanceUpdate(openid string) {
    balanceClientsMux.RLock()
    clients := balanceClients[openid]
    balanceClientsMux.RUnlock()
    
    if len(clients) == 0 {
        return // 没有活跃连接
    }
    
    var balance float64
    err := db.QueryRow("SELECT balance FROM users WHERE openid = ?", openid).Scan(&balance)
    if err != nil {
        log.Printf("[ERROR] 获取用户余额失败: %v | OpenID: %s", err, openid)
        return
    }
    
    message := map[string]interface{}{
        "type": "balance_update",
        "balance": fmt.Sprintf("%.2f", balance),
    }
    
    jsonMsg, err := json.Marshal(message)
    if err != nil {
        log.Printf("[ERROR] 序列化余额消息失败: %v", err)
        return
    }
    
    balanceClientsMux.RLock()
    for conn := range clients {
        if err := conn.WriteMessage(websocket.TextMessage, jsonMsg); err != nil {
            log.Printf("[ERROR] 发送余额消息失败: %v", err)
        }
    }
    balanceClientsMux.RUnlock()
}
func closeOrderWebSockets(orderID string) {
    clientsMutex.Lock()
    defer clientsMutex.Unlock()
    
    // 检查该订单是否有活跃连接
    if orderConns, exists := clients[orderID]; exists {
        // 给所有连接发送关闭通知，区分打手和老板
        bossCloseMessage := []byte(`{"type":"system","content":"订单已被更换，聊天已关闭"}`)
        hitterCloseMessage := []byte(`{"type":"system","content":"订单已结束，老板已更换车队"}`)
        
        for conn, client := range orderConns {
            // 根据角色发送不同消息
            var closeMessage []byte
            if client.role == "boss" {
                closeMessage = bossCloseMessage
            } else {
                closeMessage = hitterCloseMessage
            }
            
            // 尝试发送关闭消息
            err := conn.WriteMessage(websocket.TextMessage, closeMessage)
            if err != nil {
                // 忽略发送错误，继续关闭连接
            }
            
            // 关闭连接
            conn.Close()
        }
        
        // 从全局map中删除该订单的所有连接
        delete(clients, orderID)
    }
}
func CheckOrderRedirect() gin.HandlerFunc {
    return func(c *gin.Context) {
        orderID := c.Param("order_id")
        if orderID == "" {
            c.Next()
            return
        }
        
        // 获取用户角色，默认为boss
        role := c.Query("role")
        if role == "" {
            // 从路径中判断角色
            if strings.Contains(c.Request.URL.Path, "/hitt/") {
                role = "hitter"
            } else {
                role = "boss"
            }
        }
        
        // 打手不需要重定向，因为更换了打手
        if role == "hitter" {
            c.Next()
            return
        }

        // 首先检查当前订单是否已失效
        var isActive int
        var groupUserNickName string
        err := db.QueryRow(`
            SELECT IsActive, GroupUserNickName
            FROM Bridges WHERE ID = ?
        `, orderID).Scan(&isActive, &groupUserNickName)

        if err != nil {
            // 发生错误，继续正常流程
            c.Next()
            return
        }

        // 如果订单已失效，查找该用户的最新订单
        if isActive == 0 && groupUserNickName != "" {
            var newOrderID string
            err := db.QueryRow(`
                SELECT ID FROM Bridges 
                WHERE GroupID = ? AND GroupUserNickName = ? AND IsActive = 1 
                ORDER BY CreatedAt DESC LIMIT 1
            `, "网站", groupUserNickName).Scan(&newOrderID)

            if err == nil && newOrderID != "" && newOrderID != orderID {
                // 保留原始查询参数
                query := c.Request.URL.Query()
                redirectURL := fmt.Sprintf("/boss/%s", newOrderID)
                
                // 添加查询参数
                if len(query) > 0 {
                    redirectURL += "?" + query.Encode()
                }
                
                // 添加重定向标志
                if !query.Has("redirected") {
                    if strings.Contains(redirectURL, "?") {
                        redirectURL += "&redirected=true"
                    } else {
                        redirectURL += "?redirected=true"
                    }
                }
                
                c.Redirect(http.StatusFound, redirectURL)
                c.Abort()
                return
            }
        }

        // 继续正常流程
        c.Next()
    }
}
func parseMessageContent(raw []byte) (string, bool) {
    type msgStruct struct {
        Message string `json:"message"`
    }
    var msg msgStruct
    
    isJSON := false
    if err := json.Unmarshal(raw, &msg); err == nil && msg.Message != "" {
        isJSON = true
        return msg.Message, isJSON
    }
    return string(raw), isJSON
}
// Gin限流中间件
func RateLimitMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        if !limiter.Allow() {
            c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
                "error": "请求过于频繁，请稍后再试",
            })
            return
        }
        c.Next()
    }
}
func generateAnonymousID() string {
    return fmt.Sprintf("anon-%d-%s", time.Now().Unix(), uuid.New().String()[:8])
}

// 统一订单检查中间件
func CheckOrderExist() gin.HandlerFunc {
    return func(c *gin.Context) {
        orderID := c.Param("order_id")
        
        var exists bool
        err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM Bridges WHERE ID = ?)", orderID).Scan(&exists)
        if err != nil {
            c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
            return
        }
        
        if !exists {
            c.HTML(http.StatusNotFound, "error.html", gin.H{
                "ErrorMessage": "该订单不存在，请确认是否下单",
            })
            c.Abort()
            return
        }
        
        c.Next()
    }
}

// 保存消息到数据库（兼容新旧消息格式）
func saveMessageToDB(orderID string, role string, message string) {
    _, err := db.Exec(`
        INSERT INTO BridgeMessages (BridgeID, Role, Message)
        VALUES (?, ?, ?)
    `, orderID, role, html.EscapeString(message))
    
    if err != nil {
        log.Println("数据库写入失败:", err)
    }
}

func sendHistoryMessages(orderID string, conn *websocket.Conn) {
    rows, err := db.Query(`
        SELECT Role, Message, Timestamp 
        FROM BridgeMessages 
        WHERE BridgeID = ? 
        ORDER BY Timestamp ASC
    `, orderID)
    
    if err != nil {
        return
    }
    defer rows.Close()

    for rows.Next() {
        var role, message, timestamp string
        if err := rows.Scan(&role, &message, &timestamp); err != nil {
            continue
        }
        
        msg := map[string]interface{}{
            "type":      "history",
            "role":      role,
            "message":   message,
            "timestamp": timestamp,
        }
        conn.WriteJSON(msg)
    }
}

// 广播消息
func broadcastMessage(orderID string, senderRole string, message string, senderConn *websocket.Conn) {
    clientsMutex.RLock()
    defer clientsMutex.RUnlock()

    for conn, _ := range clients[orderID] {

        msg := map[string]interface{}{
            "type":      "message",
            "role":      senderRole,
            "message":   message,
            "timestamp": time.Now().Format(time.RFC3339),
        }
        
        go func(c *websocket.Conn) {
            if err := c.WriteJSON(msg); err != nil {
                log.Println("消息发送失败:", err)
            }
        }(conn)
    }
}

func handleWeChatNotification(orderID string, message string, senderRole string) {
    // 仅处理老板发送的消息
    if !isBossRole(senderRole) {
        return
    }

    var weChatUser string
    err := db.QueryRow("SELECT WeChatUser FROM Bridges WHERE ID = ?", orderID).Scan(&weChatUser)
    if err != nil {
        return
    }

    if userName, err := findUserNameByNickName(weChatUser); err == nil {
        sendTextMessage(message, userName)
        additionalMsg := fmt.Sprintf("%s:上面老板#APP，发的，私加老板免单举报，打完发#结账", orderID)
        sendTextMessage(additionalMsg, userName)
    }
}

// 角色判断函数
func isBossRole(role string) bool {
    // 支持中英文角色标识
    normalizedRole := strings.ToLower(strings.TrimSpace(role))
    return normalizedRole == "boss" || normalizedRole == "老板"
}

func luyou2() {
    r := gin.Default()
    r.Static("/shuoming", "./shuoming")
    // 只加载 HTML 文件
    r.LoadHTMLGlob("templates/*.html")
    r.Static("/image", "./image")
    r.Static("/voice", "./voice")
    r.Static("/js", "./js")
    r.Static("/css", "./css")
    r.Static("/images", "./images")
    r.Static("/static", "./static")
    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })
    // 动态路由，根据表名显示表内容
    r.GET("/table/:name", func(c *gin.Context) {
        tableName := c.Param("name")
        rows, err := db.Query("SELECT * FROM " + tableName)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        columns, err := rows.Columns()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        results := make([]map[string]interface{}, 0)
        values := make([]interface{}, len(columns))
        valuePtrs := make([]interface{}, len(columns))

        for rows.Next() {
            for i := range columns {
                valuePtrs[i] = &values[i]
            }

            rows.Scan(valuePtrs...)

            entry := make(map[string]interface{})
            for i, col := range columns {
                var v interface{}
                val := values[i]
                b, ok := val.([]byte)
                if ok {
                    v = string(b)
                } else {
                    v = val
                }
                entry[col] = v
            }
            results = append(results, entry)
        }
        c.JSON(http.StatusOK, results)
    })

    // 添加充值管理页面的路由
    r.GET("/recharge/manage", func(c *gin.Context) {
        // 将当前接单状态传递到前端
        c.HTML(http.StatusOK, "recharge_manage.html", gin.H{
            "isInternalOrder": isInternalOrderMode,
        }) // 确保有一个名为recharge_manage.html的模板文件
    })
    // 路由来切换接单模式
    r.GET("/toggle-order-mode", func(c *gin.Context) {
        isInternalOrderMode = !isInternalOrderMode
        c.JSON(http.StatusOK, gin.H{
            "isInternalOrder": isInternalOrderMode,
            "message": "接单模式已更新。",
        })
    })
    
    // 查询充值总额，计算所有充值码的总额，不考虑是否已使用
    r.GET("/recharge/total", func(c *gin.Context) {
        var total float64
        err := db.QueryRow("SELECT SUM(amount) FROM recharge_records WHERE used = 1").Scan(&total)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法获取总额"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"total": total})
    })

    // 列出所有未使用的充值码
    r.GET("/recharge/unused", func(c *gin.Context) {
        type UnusedCode struct {
            Code   string  `json:"code"`
            Amount float64 `json:"amount"`
        }
        var unusedCodes []UnusedCode

        rows, err := db.Query("SELECT recharge_code, amount FROM recharge_records WHERE used = 0")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
            return
        }
        defer rows.Close()

        for rows.Next() {
            var code UnusedCode
            if err := rows.Scan(&code.Code, &code.Amount); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "扫描失败"})
                return
            }
            unusedCodes = append(unusedCodes, code)
        }
        c.JSON(http.StatusOK, unusedCodes)
    })    

    // 注销充值码
    r.POST("/recharge/cancel", func(c *gin.Context) {
        var requestBody CancelRequestBody
        if err := c.BindJSON(&requestBody); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误"})
            return
        }

        rechargeCode := requestBody.Code
        result, err := db.Exec("UPDATE recharge_records SET used = 2 WHERE recharge_code = ? AND used = 0", rechargeCode)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "注销失败"})
            return
        }
        rowsAffected, _ := result.RowsAffected()
        if rowsAffected == 0 {
            c.JSON(http.StatusNotFound, gin.H{"error": "充值码不存在或已被使用"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"success": true, "message": "充值码已成功注销"})
    })

    // 添加新的充值码
    r.POST("/recharge/add", func(c *gin.Context) {
        var req rechargeRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无效的金额格式"})
            return
        }
        amountReal := float64(req.Amount) / 1.0
        rechargeCode := generateRechargeCode()
        _, err := db.Exec("INSERT INTO recharge_records (amount, recharge_code, used) VALUES (?, ?, 0)", amountReal, rechargeCode)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "添加失败"})
            return
        }
        c.JSON(http.StatusOK, gin.H{"success": true, "code": rechargeCode})
    })

    r.POST("/recharge/cancel-all", func(c *gin.Context) {
        // 开启一个事务
        tx, err := db.Begin()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法开始事务"})
            return
        }
        
        // 选择所有未使用的充值码
        rows, err := tx.Query("SELECT recharge_code FROM recharge_records WHERE used = 0")
        if err != nil {
            tx.Rollback() // 查询出错，回滚事务
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询未使用的充值码失败"})
            return
        }
        defer rows.Close()

        // 遍历所有未使用的充值码，更新它们的状态为已使用
        for rows.Next() {
            var code string
            if err := rows.Scan(&code); err != nil {
                tx.Rollback() // 扫描出错，回滚事务
                c.JSON(http.StatusInternalServerError, gin.H{"error": "扫描充值码失败"})
                return
            }

            if _, err := tx.Exec("UPDATE recharge_records SET used = 1 WHERE recharge_code = ?", code); err != nil {
                tx.Rollback() // 更新出错，回滚事务
                c.JSON(http.StatusInternalServerError, gin.H{"error": "注销充值码失败"})
                return
            }
        }

        // 所有充值码更新完成，提交事务
        if err := tx.Commit(); err != nil {
            tx.Rollback() // 提交事务出错，回滚事务
            c.JSON(http.StatusInternalServerError, gin.H{"error": "提交事务失败"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": true, "message": "所有充值码已成功注销"})
    })
    r.GET("/Bridges/manage", func(c *gin.Context) {
        log.Println("Fetching all orders for management view.")
        
        // 定义获取数据的函数
        fetchData := func(condition string) ([]Order, error) {
            var orders []Order
            query := fmt.Sprintf("SELECT * FROM Bridges WHERE %s ORDER BY CreatedAt DESC", condition)
            rows, err := db.Query(query)
            if err != nil {
                return nil, err
            }
            defer rows.Close()
            
            for rows.Next() {
                var order Order
                if err := rows.Scan(
                    &order.ID, &order.GroupID, &order.GroupName, &order.GroupUserNickName, 
                    &order.WeChatUser, &order.IsActive, &order.IsCompleted, &order.Msg, 
                    &order.GameID, &order.Stars, &order.StarCost, &order.OrderType, 
                    &order.CreatedAt, &order.LastMessageTime, &order.FinalRank, &order.WeChatUsername); err != nil {
                    return nil, err
                }
                orders = append(orders, order)
            }
            return orders, nil
        }
        
        // 获取各种订单状态的数据
        issuingOrders, err := fetchData("COALESCE(WeChatUser, '') = ''")
        if err != nil {
            log.Printf("Error fetching issuing orders: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch issuing orders"})
            return
        }
        
        activeOrders, err := fetchData("WeChatUser != '' AND GameID = ''")
        if err != nil {
            log.Printf("Error fetching active orders: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch active orders"})
            return
        }
        
        completedOrders, err := fetchData("GameID != ''")
        if err != nil {
            log.Printf("Error fetching completed orders: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch completed orders"})
            return
        }
        
        // 将数据传递给前端模板
        c.HTML(http.StatusOK, "Bridges.html", gin.H{
            "issuingOrders": issuingOrders,
            "activeOrders": activeOrders,
            "completedOrders": completedOrders,
        })
    })
    r.GET("/order-types", func(c *gin.Context) {
        orderTypes := []string{"代练", "陪玩", "小姐姐", "车队"}
        typeCounts := make(map[string]int)
        for _, typ := range orderTypes {
            var count int
            err := db.QueryRow("SELECT COUNT(*) FROM Bridges WHERE OrderType = ?", typ).Scan(&count)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询错误"})
                return
            }
            typeCounts[typ] = count
        }
        c.JSON(http.StatusOK, typeCounts)
    })

    r.GET("/orders/type/:type", func(c *gin.Context) {
        orderType := c.Param("type")
        var issuingOrders, activeOrders, completedOrders []Order

        // 正在发单的订单，WeChatUser 为空
        issuingQuery := "SELECT * FROM Bridges WHERE OrderType = ? AND COALESCE(WeChatUser, '') = '' ORDER BY CreatedAt DESC"
        issuingRows, err := db.Query(issuingQuery, orderType)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询正在发单的订单失败"})
            return
        }
        extractOrders(issuingRows, &issuingOrders)
        issuingRows.Close()

        // 正在进行的订单，WeChatUser 不为空，GameID 为空
        activeQuery := "SELECT * FROM Bridges WHERE OrderType = ? AND WeChatUser != '' AND GameID = '' ORDER BY CreatedAt DESC"
        activeRows, err := db.Query(activeQuery, orderType)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询进行中的订单失败"})
            return
        }
        extractOrders(activeRows, &activeOrders)
        activeRows.Close()

        // 已完成的订单，WeChatUser 不为空，GameID 不为空
        completedQuery := "SELECT * FROM Bridges WHERE OrderType = ? AND GameID != '' ORDER BY CreatedAt DESC"
        completedRows, err := db.Query(completedQuery, orderType)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询已完成的订单失败"})
            return
        }
        extractOrders(completedRows, &completedOrders)
        completedRows.Close()

        c.HTML(http.StatusOK, "orders_by_type.html", gin.H{
            "type": orderType,
            "issuingOrders": issuingOrders,
            "activeOrders": activeOrders,
            "completedOrders": completedOrders,
        })
    })  

    r.GET("/orders/dates", func(c *gin.Context) {
        var dates []string
        // 选择唯一的日期并按日期降序排序
        query := "SELECT DISTINCT strftime('%Y-%m-%d', CreatedAt) AS Date FROM Bridges ORDER BY Date DESC"
        rows, err := db.Query(query)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法查询订单日期"})
            return
        }
        defer rows.Close()
        for rows.Next() {
            var date string
            if err := rows.Scan(&date); err == nil {
                dates = append(dates, date)
            }
        }
        c.JSON(http.StatusOK, dates)
    })    

    r.GET("/orders/by-date/:date", func(c *gin.Context) {
        date := c.Param("date")
        var issuingOrders, activeOrders, completedOrders []Order
        // 正在发单的订单，WeChatUser 为空
        issuingQuery := "SELECT * FROM Bridges WHERE strftime('%Y-%m-%d', CreatedAt) = ? AND COALESCE(WeChatUser, '') = '' ORDER BY CreatedAt DESC"
        issuingRows, err := db.Query(issuingQuery, date)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询正在发单的订单失败"})
            return
        }
        defer issuingRows.Close() 
        extractOrders(issuingRows, &issuingOrders) 

        // 查询进行中的订单，这里假设 GameID 为空表示订单正在进行
        activeQuery := "SELECT * FROM Bridges WHERE strftime('%Y-%m-%d', CreatedAt) = ? AND WeChatUser != '' AND GameID = '' ORDER BY CreatedAt DESC"
        activeRows, err := db.Query(activeQuery, date)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询进行中的订单失败: " + err.Error()})
            return
        }
        defer activeRows.Close()
        extractOrders(activeRows, &activeOrders)

        // 查询已完成的订单，这里假设 GameID 非空表示订单已完成
        completedQuery := "SELECT * FROM Bridges WHERE strftime('%Y-%m-%d', CreatedAt) = ? AND GameID != '' ORDER BY CreatedAt DESC"
        completedRows, err := db.Query(completedQuery, date)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询已完成的订单失败: " + err.Error()})
            return
        }
        defer completedRows.Close()
        extractOrders(completedRows, &completedOrders)

        // 向前端发送数据，包括日期、进行中的订单和已完成的订单
        c.HTML(http.StatusOK, "orders_by_date.html", gin.H{
            "date": date,
            "issuingOrders": issuingOrders,
            "activeOrders": activeOrders,
            "completedOrders": completedOrders,
        })
    })
        
    // 增加价格
    r.POST("/orders/increase-price/:id", func(c *gin.Context) {
        id := c.Param("id")

        // 先获取当前的Msg
        var currentMsg string
        err := db.QueryRow("SELECT Msg FROM Bridges WHERE ID = ?", id).Scan(&currentMsg)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取当前信息失败", "details": err.Error()})
            return
        }

        // 正则表达式匹配价格部分
        re := regexp.MustCompile(`(单价：)(\d+)`)
        matches := re.FindStringSubmatch(currentMsg)
        if matches == nil || len(matches) < 3 {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "价格信息格式不正确"})
            return
        }

        // 转换价格并增加
        price, err := strconv.Atoi(matches[2])
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "价格转换失败", "details": err.Error()})
            return
        }
        newPrice := price + 1
        updatedMsg := re.ReplaceAllString(currentMsg, `${1}`+strconv.Itoa(newPrice))

        // 更新数据库
        _, err = db.Exec("UPDATE Bridges SET Msg = ? WHERE ID = ?", updatedMsg, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新价格失败", "details": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"message": "价格增加成功", "newMsg": updatedMsg})
    })


    // 减少价格
    r.POST("/orders/decrease-price/:id", func(c *gin.Context) {
        id := c.Param("id")

        // 先获取当前的Msg
        var currentMsg string
        err := db.QueryRow("SELECT Msg FROM Bridges WHERE ID = ?", id).Scan(&currentMsg)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取当前信息失败", "details": err.Error()})
            return
        }

        // 正则表达式匹配价格部分
        re := regexp.MustCompile(`(单价：)(\d+)`)
        matches := re.FindStringSubmatch(currentMsg)
        if matches == nil || len(matches) < 3 {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "价格信息格式不正确"})
            return
        }

        // 转换价格并减少
        price, err := strconv.Atoi(matches[2])
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "价格转换失败", "details": err.Error()})
            return
        }
        newPrice := price - 1
        if newPrice < 0 { // 价格不应该为负数，可以根据业务需求调整这里的逻辑
            newPrice = 0
        }
        updatedMsg := re.ReplaceAllString(currentMsg, `${1}`+strconv.Itoa(newPrice))

        // 更新数据库
        _, err = db.Exec("UPDATE Bridges SET Msg = ? WHERE ID = ?", updatedMsg, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新价格失败", "details": err.Error()})
            return
        }
        c.JSON(http.StatusOK, gin.H{"message": "价格减少成功", "newMsg": updatedMsg})
    })
    // 设置新的POST路由处理提醒消息
    r.POST("/api/alert-user", func(c *gin.Context) {
        var req struct {
            WeChatUser string `json:"weChatUser"`
        }
        if err := c.BindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求数据不正确"})
            return
        }

        userName, err := findUserNameByNickName(req.WeChatUser) // 假设 self 可以为 nil 或根据实际情况传递
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查找用户失败"})
            return
        }

        content := "哥，打完了的话发送#结账，根据提示记录，就可以自动记录结账"
        sendTextMessage(fmt.Sprintf(content), userName) // 同样假设 self 可以为 nil 或根据实际情况传递

        c.JSON(http.StatusOK, gin.H{"message": "提醒消息已发送"})
    })
    r.POST("/api/alert-all-users", func(c *gin.Context) {
        var req struct {
            WeChatUsers []string `json:"weChatUsers"` // 从请求体中接收一个用户昵称列表
        }
        if err := c.BindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
            return
        }
    
        // 循环处理每一个用户
        for _, user := range req.WeChatUsers {
            userName, err := findUserNameByNickName(user) // 使用变量user而不是req.WeChatUser
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("查找用户 %s 失败", user)})
                continue // 如果查找失败，继续处理下一个用户
            }
    
            content := "哥，打完了的话发送#结账，根据提示记录，就可以自动记录结账"
            sendTextMessage(fmt.Sprintf(content), userName) // 假设replyToUser是发送消息的函数
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "所有提醒消息已成功发送"})
    })    
    r.POST("/api/remind", func(c *gin.Context) {
        var req struct {
            Creditors []string `json:"creditors"`
        }
        if err := c.BindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
    
        // 循环处理每一个用户
        for _, user := range req.Creditors {
            userName, err := findUserNameByNickName(user) // 使用变量user而不是req.WeChatUser
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("查找用户 %s 失败", user)})
                continue // 如果查找失败，继续处理下一个用户
            }
    
            content := "哥，你还没结账，请尽快结账，来自：" + "国服梦奇"
            sendTextMessage(fmt.Sprintf(content), userName) // 假设replyToUser是发送消息的函数
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "提醒成功"})
    })
    r.POST("/api/complaint", func(c *gin.Context) {
        var req struct {
            Creditor   string `json:"creditor"`
            Complaint  string `json:"complaint"`
        }
    
        // 记录请求进入的日志
        log.Println("Received POST request at /api/complaint")
    
        // 绑定 JSON 请求体
        if err := c.BindJSON(&req); err != nil {
            log.Printf("Failed to bind JSON: %v", err)  // 记录错误日志
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
    
        log.Printf("Received complaint: Creditor=%s, Complaint=%s", req.Creditor, req.Complaint)
    
        // 检查指定昵称的用户是否存在
        userName, err := findUserNameByNickName("国1车队联系员-梦奇（24小时ai在）")
        if err != nil {
            log.Printf("User not found: %v", err)  // 记录用户未找到的日志
            c.JSON(http.StatusNotFound, gin.H{"error": "User not found", "redirectTo": "/scan_page1"})
            return
        }
    
        log.Printf("User found: %s", userName)
    
        // 如果用户存在，发送消息
        message := "收到投诉用户：" + req.Creditor + "\n内容:" + req.Complaint
        sendTextMessage(fmt.Sprintf(message), userName)
    
        log.Println("Message successfully sent to user")
        c.JSON(http.StatusOK, gin.H{"message": "投诉已提交"})
    })
    
    // 切换订单的激活状态
    r.POST("/orders/toggle-active/:id", func(c *gin.Context) {
        id := c.Param("id")

        // 获取当前激活状态
        var isActive bool
        err := db.QueryRow("SELECT IsActive FROM Bridges WHERE ID = ?", id).Scan(&isActive)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "获取当前状态失败", "details": err.Error()})
            return
        }

        // 切换状态
        newStatus := !isActive
        _, err = db.Exec("UPDATE Bridges SET IsActive = ? WHERE ID = ?", newStatus, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "更新状态失败", "details": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "状态更新成功", "newStatus": newStatus})
    })
    r.DELETE("/orders/delete/:orderId", func(c *gin.Context) {
        orderId := c.Param("orderId")

        result, err := db.Exec("DELETE FROM bridges WHERE id = ?", orderId)
        if err != nil {
            // 输出 SQL 错误，便于调试
            log.Printf("Error deleting order with ID %s: %v", orderId, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Error deleting order", "details": err.Error()})
            return
        }
    
        rowsAffected, err := result.RowsAffected()
        if err != nil {
            // 输出影响行数错误，便于调试
            log.Printf("Error getting rows affected for order ID %s: %v", orderId, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Error checking deletion result", "details": err.Error()})
            return
        }
    
        if rowsAffected == 0 {
            c.JSON(http.StatusNotFound, gin.H{"error": "No order found with the given ID"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"message": "Order successfully deleted"})
    })
    r.GET("/UnsettledBridges/manage", func(c *gin.Context) {
        unsettledResults, err := handleRecords(db, false)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法加载未结账记录"})
            return
        }

        settledResults, err := handleRecords(db, true)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法加载已结账记录"})
            return
        }

        c.HTML(http.StatusOK, "UnsettledBridges_manage.html", gin.H{
            "UnsettledData": unsettledResults,
            "SettledData": settledResults,
        })
    })    

    r.POST("/mark-settled/:id", func(c *gin.Context) {
        // 记录请求开始
        startTime := time.Now()
        bridgeID := c.Param("id")
        log.Printf("[mark-settled] 请求开始 | bridgeID:%s", bridgeID)
        
        // 记录原始参数
        log.Printf("[mark-settled] 原始参数 | bridgeID:%s | 完整URL:%s", 
            bridgeID, c.Request.URL.String())
        
        // 开始事务
        tx, err := db.Begin()
        if err != nil {
            log.Printf("[mark-settled] 开始事务失败 | error:%v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "开始事务失败"})
            return
        }
        
        // 获取订单信息包括结算金额
        var totalPayment float64
        var weChatUser string
        
        // 从Expenditures表获取总支付金额
        log.Printf("[mark-settled] 查询Expenditures表 | SQL:%q | 参数:%s",
            "SELECT SUM(Payment) FROM Expenditures WHERE BridgeID = ?", bridgeID)
            
        err = tx.QueryRow("SELECT SUM(Payment) FROM Expenditures WHERE BridgeID = ?", bridgeID).Scan(&totalPayment)
        if err != nil {
            tx.Rollback()
            log.Printf("[mark-settled] 查询Expenditures表失败 | bridgeID:%s | error:%v", bridgeID, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询订单金额信息失败", "detail": err.Error()})
            return
        }
        
        err = tx.QueryRow("SELECT WeChatUsername FROM Bridges WHERE ID = ?", bridgeID).Scan(&weChatUser)
        if err != nil {
            tx.Rollback()
            log.Printf("[mark-settled] 查询UnsettledBridges表失败 | bridgeID:%s | error:%v", bridgeID, err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "查询WeChat用户名失败", "detail": err.Error()})
            return
        }
        
        // 数据库更新操作
        log.Printf("[mark-settled] 执行数据库更新 | SQL:%q | 参数:%s",
            "UPDATE UnsettledBridges SET IsSettled = 1, SettlementTime = ? WHERE ID = ?", bridgeID)
            
        result, err := tx.Exec("UPDATE UnsettledBridges SET IsSettled = 1, SettlementTime = ? WHERE ID = ?", 
                            time.Now().Format("2006-01-02 15:04:05"), bridgeID)
        if err != nil {
            tx.Rollback()
            log.Printf("[mark-settled] 数据库更新失败 | bridgeID:%s | error:%v", bridgeID, err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "error":  "Database update failed",
                "detail": err.Error(),
            })
            return
        }
        
        // 记录影响行数
        rowsAffected, _ := result.RowsAffected()
        log.Printf("[mark-settled] 更新结果 | bridgeID:%s | 影响行数:%d", bridgeID, rowsAffected)
        
        if rowsAffected == 0 {
            tx.Rollback()
            log.Printf("[mark-settled] 警告: 未找到匹配记录 | bridgeID:%s", bridgeID)
            c.JSON(http.StatusNotFound, gin.H{
                "error":  "未找到匹配记录",
                "detail": fmt.Sprintf("ID为 %s 的记录不存在或已标记为已结算", bridgeID),
            })
            return
        }
        
        // 确保WeChatUser不为空
        if weChatUser == "" {
            tx.Rollback()
            log.Printf("[mark-settled] 无WeChat用户关联 | bridgeID:%s", bridgeID)
            c.JSON(http.StatusNotFound, gin.H{"error": "No WeChat username associated with this bridge"})
            return
        }
        
        // 查询接收方是否已注册
        var receiverOpenID string
        var receiverExists bool = true
        err = tx.QueryRow("SELECT openid FROM users WHERE wechatname = ?", weChatUser).Scan(&receiverOpenID)
        if err != nil {
            if err == sql.ErrNoRows {
                // 用户不存在，将使用临时表记录
                receiverExists = false
                log.Printf("[mark-settled] 接收方用户 %s 未注册，将使用临时表记录", weChatUser)
            } else {
                tx.Rollback()
                log.Printf("[mark-settled] 查询接收方用户失败 | weChatUser:%s | error:%v", weChatUser, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "查询接收方用户失败"})
                return
            }
        }
        
        // 生成唯一的交易ID
        transactionUUID := uuid.New().String()
        
        if receiverExists {
            // 用户存在，直接增加余额
            _, err = tx.Exec("UPDATE users SET balance = balance + ? WHERE openid = ?", 
                            totalPayment, receiverOpenID)
            if err != nil {
                tx.Rollback()
                log.Printf("[mark-settled] 更新接收方余额失败 | weChatUser:%s | error:%v", weChatUser, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "更新接收方余额失败"})
                return
            }
            
            // 插入交易记录 - 收款方（已注册用户）
            receiverTransactionUUID := uuid.New().String()
            _, err = tx.Exec(
                `INSERT INTO UserTransactions 
                (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, RelatedOrderID, TransactionID, CreateTime) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                receiverTransactionUUID,
                receiverOpenID,
                "手动结账收款",
                totalPayment, // 正数表示收入
                0,           // 服务费
                totalPayment, // 实际金额
                "成功",
                bridgeID,
                transactionUUID,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[mark-settled] 插入收款方交易记录失败 | weChatUser:%s | error:%v", weChatUser, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "插入收款方交易记录失败"})
                return
            }
            
            // 尝试发送WebSocket通知更新余额 - 收款方
            notifyBalanceUpdate(receiverOpenID)
        } else {
            // 修改代码使用TempUserBalances表而不是PendingPayments表
            _, err = tx.Exec(
                `INSERT INTO TempUserBalances 
                (WeChatUsername, Balance, LastUpdateTime) 
                VALUES (?, ?, ?)
                ON CONFLICT(WeChatUsername) DO UPDATE SET
                Balance = Balance + ?,
                LastUpdateTime = ?`,
                weChatUser,
                totalPayment,
                time.Now().Format("2006-01-02 15:04:05"),
                totalPayment,
                time.Now().Format("2006-01-02 15:04:05"),
            )
            
            if err != nil {
                tx.Rollback()
                log.Printf("[mark-settled] 添加到临时支付表失败 | weChatUser:%s | error:%v", weChatUser, err)
                c.JSON(http.StatusInternalServerError, gin.H{"error": "添加到临时支付表失败"})
                return
            }
        }
        
        // 还需要获取WeChatUser用于发消息
        var messageUser string
        // 从UnsettledBridges表获取WeChatUser
        err = tx.QueryRow("SELECT WeChatUser FROM UnsettledBridges WHERE ID = ?", bridgeID).Scan(&messageUser)
        if err != nil {
            log.Printf("[mark-settled] 获取WeChatUser失败 | bridgeID:%s | error:%v", bridgeID, err)
            // 不终止事务，继续执行
        } else if messageUser != "" {
            // 查找用户名并发送消息
            userName, err := findUserNameByNickName(messageUser)
            if err != nil {
                log.Printf("[mark-settled] 查找用户失败 | messageUser:%s | error:%v", messageUser, err)
                // 不终止事务，继续执行
            } else {
                // 发送结算确认消息
                content := "订单已结清，请注意查看，下次还望继续合作，哥！"
                sendTextMessage(content, userName)
            }
        }
        
        log.Printf("[mark-settled] 开始更新支付状态 | bridgeID:%s", bridgeID)
        if _, err := UpdatePaymentStatus(bridgeID); err != nil {
            tx.Rollback()
            log.Printf("[mark-settled] 支付状态更新失败 | bridgeID:%s | error:%v", bridgeID, err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "error":  "支付状态更新失败",
                "detail": err.Error(),
            })
            return
        }
        
        // 提交事务
        if err = tx.Commit(); err != nil {
            tx.Rollback()
            log.Printf("[mark-settled] 提交事务失败 | error:%v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "提交事务失败"})
            return
        }
        
        // 记录请求完成
        log.Printf("[mark-settled] 请求完成 | bridgeID:%s | 耗时:%v | 用户已注册:%v",
            bridgeID, time.Since(startTime), receiverExists)
        
        c.JSON(http.StatusOK, gin.H{
            "message": "订单已结",
            "userRegistered": receiverExists,
            "transactionID": transactionUUID,
            "amount": totalPayment,
        })
    })
    r.POST("/api/update_playmate", func(c *gin.Context) {
        var json struct {
            PlaymateIndex int    `json:"playmateIndex"`
            ID            string `json:"id"`
            Description   string `json:"description"`
            Price         int    `json:"price"` // 将Price字段更改为整数类型
        }
    
        // 绑定JSON并打印日志
        if err := c.ShouldBindJSON(&json); err != nil {
            log.Printf("JSON绑定错误: %v", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        log.Printf("接收到的数据: %+v", json)
    
        // 准备并执行SQL语句
        stmt, err := db.Prepare("UPDATE playmates SET id = ?, text = ?, price = ? WHERE playmateID = ?")
        if err != nil {
            log.Printf("准备SQL语句错误: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库操作失败"})
            return
        }
        defer stmt.Close()
    
        _, err = stmt.Exec(json.ID, json.Description, json.Price, json.PlaymateIndex)
        if err != nil {
            log.Printf("执行SQL语句错误: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库操作失败"})
            return
        }
    
        log.Printf("陪玩编号 %d 更新成功", json.PlaymateIndex)
        c.JSON(http.StatusOK, gin.H{"message": "更新成功"})
    })    
    r.POST("/copy_rank_prices", func(c *gin.Context) {
        db2, err := sql.Open("sqlite3", "./data.db")
        if err != nil {
            log.Fatal(err)
        }
        defer db2.Close()
        rows, err := db.Query("SELECT Rank, Price, StarCost, RankOrder FROM RankPrices")
        if err != nil {
            log.Printf("Error querying db: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        tx, err := db2.Begin()
        if err != nil {
            log.Printf("Error beginning transaction in db2: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        _, err = tx.Exec("DELETE FROM RankPrices")
        if err != nil {
            log.Printf("Error deleting old records in db2: %v\n", err)
            tx.Rollback()
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        for rows.Next() {
            var rank string
            var price, starCost, rankOrder int
            if err := rows.Scan(&rank, &price, &starCost, &rankOrder); err != nil {
                log.Printf("Error scanning row: %v\n", err)
                tx.Rollback()
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }

            _, err := tx.Exec("INSERT INTO RankPrices (Rank, Price, StarCost, RankOrder) VALUES (?, ?, ?, ?)", rank, price, starCost, rankOrder)
            if err != nil {
                log.Printf("Error inserting new record in db2: %v\n", err)
                tx.Rollback()
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
        }

        if err := tx.Commit(); err != nil {
            log.Printf("Error committing transaction in db2: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"status": "success"})
    })

    r.POST("/update_rank_prices", func(c *gin.Context) {
        resp, err := http.Get("http://www.moki-flanke.icu:8080/api/rankprices")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer resp.Body.Close()

        var rankPrices []struct {
            Rank      string `json:"rank"`
            Price     int    `json:"price"`
            StarCost  int    `json:"starCost"`
            RankOrder int    `json:"rankOrder"`
        }

        if err := json.NewDecoder(resp.Body).Decode(&rankPrices); err != nil {
            log.Printf("Error decoding response: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        
        tx, err := db.Begin()
        if err != nil {
            log.Printf("Error beginning transaction in db: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        _, err = tx.Exec("DELETE FROM RankPrices")
        if err != nil {
            log.Printf("Error deleting old records in db: %v\n", err)
            tx.Rollback()
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        for _, rp := range rankPrices {
            _, err := tx.Exec("INSERT INTO RankPrices (Rank, Price, StarCost, RankOrder) VALUES (?, ?, ?, ?)", rp.Rank, rp.Price, rp.StarCost, rp.RankOrder)
            if err != nil {
                log.Printf("Error inserting new record in db: %v\n", err)
                tx.Rollback()
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
        }

        if err := tx.Commit(); err != nil {
            log.Printf("Error committing transaction in db: %v\n", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"status": "success"})
    })

    // 删除陪玩的路由
    r.POST("/api/delete_playmate", func(c *gin.Context) {
        var json struct {
            PlaymateIndex int `json:"playmateIndex"`
        }

        if err := c.ShouldBindJSON(&json); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        // 查询imagePath和filePath
        var imagePath, filePath string
        err := db.QueryRow("SELECT imagePath, filePath FROM playmates WHERE playmateID = ?", json.PlaymateIndex).Scan(&imagePath, &filePath)
        if err != nil {
            if err == sql.ErrNoRows {
                c.JSON(http.StatusNotFound, gin.H{"message": "陪玩未找到"})
            } else {
                log.Fatal(err)
            }
            return
        }

        // 删除文件
        err = os.Remove(filepath.Join(".", imagePath))
        if err != nil && !os.IsNotExist(err) {
            log.Fatal(err)
        }

        err = os.Remove(filepath.Join(".", filePath))
        if err != nil && !os.IsNotExist(err) {
            log.Fatal(err)
        }

        // 删除数据库记录
        stmt, err := db.Prepare("DELETE FROM playmates WHERE playmateID = ?")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close()

        _, err = stmt.Exec(json.PlaymateIndex)
        if err != nil {
            log.Fatal(err)
        }

        c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
    })
    r.POST("/send-reminder/:id", func(c *gin.Context) {
        bridgeID := c.Param("id")
    
        // 查询数据库获取 WeChatUser
        var weChatUser string
        err := db.QueryRow("SELECT WeChatUser FROM Bridges WHERE ID = ?", bridgeID).Scan(&weChatUser)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch WeChat user"})
            return
        }
    
        if weChatUser == "" {
            c.JSON(http.StatusNotFound, gin.H{"error": "No WeChat user associated with this bridge"})
            return
        }
        userName, err := findUserNameByNickName(weChatUser)
        if err != nil {
            fmt.Printf("查找用户失败: %v\n", err)
            return
        }
        // 调用 replyToUser 函数发送消息
        content := "哥，你还没保存收款二维码，请留下收款二维码，以便于结账"
        sendTextMessage(fmt.Sprintf(content), userName)
    
        c.JSON(http.StatusOK, gin.H{"message": "提醒已成功发送"})
    })    

    // 定义债务管理的路由
    r.GET("/debt/manage", func(c *gin.Context) {
        // 渲染债务管理页面并传递昵称
        c.HTML(http.StatusOK, "debt.html", gin.H{
            "selfNickName": "国服车队联系员-梦乐",
        })
    })

    r.GET("/current_event/manage", func(c *gin.Context) {
        // 获取 current_event 数据
        var events []map[string]interface{}
        eventsQuery := "SELECT id, event_title, event_text FROM current_event"
        eventsRows, err := db.Query(eventsQuery)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Database query for events failed: " + err.Error()})
            return
        }
        defer eventsRows.Close()
    
        for eventsRows.Next() {
            var id int
            var eventTitle, eventText string
            if err := eventsRows.Scan(&id, &eventTitle, &eventText); err != nil {
                fmt.Printf("Failed to scan events: %v\n", err) // Logging the error
                continue
            }
            events = append(events, map[string]interface{}{
                "id":          id,
                "event_title": eventTitle,
                "event_text":  eventText,
            })
        }
    
        // 检查是否有事件数据
        if len(events) == 0 {
            // 如果没有数据，则插入预定义的事件
            insertEvents := `INSERT INTO current_event (id, event_title, event_text) VALUES 
                (1, '价格表', '默认'), 
                (2, '老板群', '默认'), 
                (3, '外部发单群', '默认'),
                (4, '内部接单', '默认'),
                (5, '陪玩群', '默认'),
                (6, '小姐姐群', '默认'),
                (7, '代练群', '默认'),
                (8, 'AI名称', '默认'),
                (9, '工作室的广告', '默认'),
                (10, '已拉黑的接单用户', '默认'),
                (11, '摘星星活动群', '默认')`
            if _, err = db.Exec(insertEvents); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Error inserting default events: " + err.Error()})
                return
            }
            // 重新执行查询以获取新插入的数据
            eventsRows, err = db.Query(eventsQuery)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Database re-query for events failed: " + err.Error()})
                return
            }
            defer eventsRows.Close()
            for eventsRows.Next() {
                var id int
                var eventTitle, eventText string
                if err := eventsRows.Scan(&id, &eventTitle, &eventText); err != nil {
                    continue
                }
                events = append(events, map[string]interface{}{
                    "id":          id,
                    "event_title": eventTitle,
                    "event_text":  eventText,
                })
            }
        }
    
        // 获取 RankPrices 数据，只包括 RankOrder 在 126-250 之间以及大于等于 376 的
        var ranks []map[string]interface{}
        ranksQuery := "SELECT Rank, Price, StarCost, RankOrder FROM RankPrices WHERE (RankOrder BETWEEN 167 AND 332 OR RankOrder >= 499) ORDER BY RankOrder"
        ranksRows, err := db.Query(ranksQuery)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Database query for ranks failed: " + err.Error()})
            return
        }
        defer ranksRows.Close()
    
        for ranksRows.Next() {
            var rank string
            var price, starCost, rankOrder int
            if err := ranksRows.Scan(&rank, &price, &starCost, &rankOrder); err != nil {
                fmt.Printf("Failed to scan ranks: %v\n", err) // Logging the error
                continue
            }
            ranks = append(ranks, map[string]interface{}{
                "rank": rank,
                "price": price,
                "starCost": starCost,
                "rankOrder": rankOrder,
            })
        }
    
        // 传递数据到模板
        c.HTML(http.StatusOK, "current_event.html", gin.H{
            "events": events,
            "ranks": ranks,
        })
    })      

    r.POST("/update_event", func(c *gin.Context) {
        id := c.PostForm("id")
        newText := c.PostForm("event_text")
        if id == "" || newText == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
            return
        }

        _, err := db.Exec("UPDATE current_event SET event_text = ? WHERE id = ?", newText, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update event"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": "Event updated"})
    })

    r.POST("/add_group", func(c *gin.Context) {
        id := c.PostForm("id")
        newGroup := c.PostForm("new_group")
        if id == "" || newGroup == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
            return
        }

        var currentText string
        err := db.QueryRow("SELECT event_text FROM current_event WHERE id = ?", id).Scan(&currentText)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
            return
        }

        updatedText := currentText + "||" + newGroup
        _, err = db.Exec("UPDATE current_event SET event_text = ? WHERE id = ?", updatedText, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update event"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": "Group added"})
    })

    r.POST("/update_bulk", func(c *gin.Context) {
        var ranks []string
        if err := c.BindJSON(&ranks); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
            return
        }
        typeOfUpdate := c.Query("type") // "price" or "starCost"
        newValue, err := strconv.Atoi(c.Query("value"))
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid value for update"})
            return
        }

        // Start a transaction
        tx, err := db.Begin()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not start transaction"})
            return
        }
        defer tx.Rollback()

        for _, rank := range ranks {
            var rankOrder int
            err := tx.QueryRow("SELECT RankOrder FROM RankPrices WHERE Rank = ?", rank).Scan(&rankOrder)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve rank order"})
                return
            }

            // Update the main rank
            updateQuery := ""
            if typeOfUpdate == "price" {
                updateQuery = "UPDATE RankPrices SET Price = ? WHERE Rank = ?"
            } else if typeOfUpdate == "starCost" {
                updateQuery = "UPDATE RankPrices SET StarCost = ? WHERE Rank = ?"
            }
            if _, err := tx.Exec(updateQuery, newValue, rank); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update rank"})
                return
            }

            // If RankOrder is within the specified range, also update associated ranks
            if rankOrder >= 167 && rankOrder <= 332 {
                associatedRanksQuery := "UPDATE RankPrices SET " + typeOfUpdate + " = ? WHERE RankOrder IN (?, ?)"
                if _, err := tx.Exec(associatedRanksQuery, newValue, rankOrder+166, rankOrder-166); err != nil {
                    c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update associated ranks"})
                    return
                }
            }
        }

        // Commit the transaction
        if err := tx.Commit(); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Transaction commit failed"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Update successful"})
    })

    r.GET("/member_stars/manage", func(c *gin.Context) {
        var memberStars []map[string]interface{}
        query := `
        SELECT ms.GroupID, ms.UserName, ms.StarsCount, IFNULL(ud.Discount, 100) AS Discount,
               julianday('now') - julianday(MAX(b.CreatedAt)) AS DaysSinceLastOrder
        FROM member_stars ms
        LEFT JOIN UserDiscounts ud ON ms.UserName = ud.NickName
        LEFT JOIN Bridges b ON ms.UserName = b.GroupUserNickName
        GROUP BY ms.GroupID, ms.UserName, ms.StarsCount, ud.Discount
        `
        rows, err := db.Query(query)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()
    
        for rows.Next() {
            var GroupID, UserName string
            var StarsCount, Discount int
            var DaysSinceLastOrder sql.NullFloat64  // 使用sql.NullFloat64来处理可能的NULL值
            if err := rows.Scan(&GroupID, &UserName, &StarsCount, &Discount, &DaysSinceLastOrder); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            
            // 处理DaysSinceLastOrder的显示逻辑
            daysText := "未发单"  // 默认显示未发单
            if DaysSinceLastOrder.Valid {
                daysText = fmt.Sprintf("%.0f 天前", DaysSinceLastOrder.Float64)
            }
    
            memberStars = append(memberStars, map[string]interface{}{
                "GroupID":           GroupID,
                "UserName":          UserName,
                "StarsCount":        StarsCount,
                "Discount":          Discount,
                "DaysSinceLastOrder": daysText,  // 以字符串形式提供天数
            })
        }
    
        c.HTML(http.StatusOK, "member_stars.html", gin.H{
            "memberStars": memberStars,
        })
    })
    
    r.POST("/update_member_info", func(c *gin.Context) {
        groupID := c.PostForm("GroupID")
        userName := c.PostForm("UserName")
        starsCount := c.PostForm("StarsCount")
        discount := c.PostForm("Discount")
    
        if groupID == "" || userName == "" {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request, GroupID and UserName are required"})
            return
        }
    
        var err error
        var starsCountInt, discountInt int
    
        if starsCount != "" {
            starsCountInt, err = strconv.Atoi(starsCount)
            if err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid format for stars count"})
                return
            }
        } else {
            starsCountInt = 0 // 如果没有提供starsCount，默认为0
        }
    
        discountInt = 100 // 默认折扣值为100
        if discount != "" {
            discountInt, err = strconv.Atoi(discount)
            if err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid format for discount"})
                return
            }
        }
    
        if starsCount != "" {
            _, err = db.Exec("UPDATE member_stars SET StarsCount = ? WHERE GroupID = ? AND UserName = ?",
                starsCountInt, groupID, userName)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update star count"})
                return
            }
        }
    
        // 尝试插入或更新折扣信息
        _, err = db.Exec(`
            INSERT INTO UserDiscounts (NickName, Discount)
            VALUES (?, ?)
            ON CONFLICT(NickName) DO UPDATE SET Discount = excluded.Discount`,
            userName, discountInt)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert or update discount"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"success": "Member info updated successfully"})
    })    

    r.GET("/user_stats/manage", func(c *gin.Context) {
        var userStats []map[string]interface{}

        rows, err := db.Query("SELECT DISTINCT NickName, GroupNickNames, TotalStars, BridgeCount, CompleteOrderCount FROM user_stats ORDER BY NickName")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        for rows.Next() {
            var nickName, groupNickNames string
            var totalStars, bridgeCount, completeOrderCount int
            if err := rows.Scan(&nickName, &groupNickNames, &totalStars, &bridgeCount, &completeOrderCount); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }

            uniqueGroups := make(map[string]struct{})
            for _, groupName := range strings.Split(groupNickNames, ",") {
                uniqueGroups[groupName] = struct{}{}
            }
            var uniqueGroupNickNames []string
            for groupName := range uniqueGroups {
                uniqueGroupNickNames = append(uniqueGroupNickNames, groupName)
            }

            completionRate := "N/A"
            if bridgeCount > 0 {
                completionRate = fmt.Sprintf("%.1f%%", float64(completeOrderCount)/float64(bridgeCount)*100)
            }

            // 查询用户的支出总和
            var totalPayment sql.NullInt64
            _ = db.QueryRow("SELECT SUM(Payment) FROM Expenditures WHERE NickName = ?", nickName).Scan(&totalPayment)
            totalPaymentStr := "无记录"
            if totalPayment.Valid {
                totalPaymentStr = fmt.Sprintf("%d", totalPayment.Int64)
            }

            userStats = append(userStats, map[string]interface{}{
                "NickName":           nickName,
                "GroupNickNames":     strings.Join(uniqueGroupNickNames, ", "),
                "TotalStars":         totalStars,
                "BridgeCount":        bridgeCount,
                "CompleteOrderCount": completeOrderCount,
                "CompletionRate":     completionRate,
                "TotalPayment":       totalPaymentStr,  // 接单总额
            })
        }

        c.HTML(http.StatusOK, "user_stats.html", gin.H{
            "UserStats": userStats,
        })
    })
    r.POST("/api/get_user_orders", func(c *gin.Context) {
        var userInput struct {
            WeChatUser string `json:"we_chat_user"` // 确保json标签与前端发送的字段匹配
        }
        if err := c.BindJSON(&userInput); err != nil {
            fmt.Println("Error binding JSON:", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON request"})
            return
        }

        fmt.Println("Received WeChat user:", userInput.WeChatUser) // 打印接收到的用户名

        var orders []Order
        rows, err := db.Query(`
            SELECT ID, GroupID, GroupName, GroupUserNickName, WeChatUser, IsActive, IsCompleted, Msg, GameID, Stars, StarCost, OrderType, CreatedAt, LastMessageTime, FinalRank
            FROM Bridges WHERE WeChatUser = ?`, userInput.WeChatUser)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        for rows.Next() {
            var order Order
            if err := rows.Scan(
                &order.ID, &order.GroupID, &order.GroupName, &order.GroupUserNickName, 
                &order.WeChatUser, &order.IsActive, &order.IsCompleted, &order.Msg, 
                &order.GameID, &order.Stars, &order.StarCost, &order.OrderType, 
                &order.CreatedAt, &order.LastMessageTime, &order.FinalRank, &order.WeChatUsername); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            orders = append(orders, order)
        }
        if len(orders) == 0 {
            c.JSON(http.StatusNotFound, gin.H{"error": "找不到该用户的订单详情，请检查记录是否已删除"})
            return
        }
        fmt.Println("Found orders:", len(orders)) // 打印找到的订单数量
        c.JSON(http.StatusOK, orders)
    })    
    // 假设你已经有一个初始化好的数据库连接 `db`
    r.POST("/add-to-blacklist", func(c *gin.Context) {
        var requestData struct {
            NickName string `json:"nickname"`
        }
        
        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误"})
            return
        }
        
        _, err := db.Exec("UPDATE current_event SET event_text = CONCAT(event_text, '||', ?) WHERE id = 10", requestData.NickName)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "无法添加到黑名单"})
            return
        }
        
        c.JSON(http.StatusOK, gin.H{"message": "添加到黑名单成功"})
    })
    // 处理订单提交
    r.POST("/validateRank/flexibleOrder", func(c *gin.Context) {
        var order FlexibleOrder
    
        if err := c.BindJSON(&order); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
            return
        }
    
        // 将 Stop 字段设置为 false
        order.Stop = false
    
        // Check if RestrictedOrderDetails is empty and set default values if needed
        if len(order.RestrictedOrderDetails) == 0 {
            order.RestrictedOrderDetails = []string{"4-1", "等", "安", "苹果", "ios"}
        }
    
        // 将订单存储到全局变量
        mu.Lock()
        orders = append(orders, order)
        mu.Unlock()
    
        c.JSON(http.StatusOK, gin.H{"message": "Order submitted successfully"})
    })
    
    r.GET("/shuomings/manage", func(c *gin.Context) {
        c.HTML(http.StatusOK, "shuoming_manage.html", nil)
    })

    r.GET("/peiwantuan/manage", func(c *gin.Context) {
        indexes, err := getMediaIndexes() // 调用新的获取媒体索引函数
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve media indexes"})
            return
        }
    
        c.HTML(http.StatusOK, "peiwantuan.html", gin.H{
            "mediaIndexes": indexes, // 将媒体索引传递给HTML页面
        })
    })    

    r.POST("/api/add_playmate", func(c *gin.Context) {
        var input struct {
            ID int `json:"id"`
        }
        if err := c.ShouldBindJSON(&input); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        addPlaymateMode = true
        currentPlaymateID = input.ID

        // 通知星标用户
        message := fmt.Sprintf("添加陪玩功能已开启，您的编号是：%d，请发送首个照片和文件。", currentPlaymateID)
        sendTextMessage(message, "Moki-Flanke")

        c.JSON(http.StatusOK, gin.H{"message": "陪玩添加成功"})
    })
    r.GET("/scan_page1", func(c *gin.Context) {
        c.HTML(http.StatusOK, "scan.html", nil) // 显示扫码页面
    })
    r.GET("/seller", func(c *gin.Context) {
        c.HTML(http.StatusOK, "seller.html", nil) // 显示扫码页面
    })
    r.GET("/bang_page", func(c *gin.Context) {
        c.HTML(http.StatusOK, "bang.html", nil) // 显示扫码页面
    })
    // 处理客服页面的路由
    r.GET("/kefu/manage", func(c *gin.Context) {
        c.HTML(http.StatusOK, "kefu_template.html", nil) // 假设您有一个名为 kefu_template.html 的 HTML 文件用于显示客服页面
    })    
    r.POST("/send_message", func(c *gin.Context) {
        var req struct {
            NickName string `json:"nickname"`  // 接收前端传来的昵称
        }
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request"})
            return
        }
    
        // 检查指定昵称的用户是否存在
        userName, err := findUserNameByNickName("国1车队联系员-梦奇（24小时ai在）")
        if err != nil {
            // 如果指定用户不存在，返回一个特定的状态码或消息
            c.JSON(http.StatusNotFound, gin.H{"error": "User not found", "redirectTo": "/scan_page1"})
            return
        }
    
        // 如果用户存在，发送消息
        message := "偷单嫌疑：" + req.NickName
        sendTextMessage(fmt.Sprintf(message), userName)
        c.JSON(http.StatusOK, gin.H{"status": "Message sent successfully"})
    })
    // 设置路由跳转到web.html页面
    r.GET("/web/manage", func(c *gin.Context) {
        rows, err := db.Query("SELECT id, seller, buyers, group_id, item_name, description, price, quantity, image_file_name FROM trade_items")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
    
        var tradeItems []map[string]interface{}
        for rows.Next() {
            var id int
            var seller, buyers, group_id, item_name, description, image_file_name sql.NullString
            var price sql.NullFloat64
            var quantity sql.NullInt64
    
            err = rows.Scan(&id, &seller, &buyers, &group_id, &item_name, &description, &price, &quantity, &image_file_name)
            if err != nil {
                log.Fatal(err)
            }
    
            item := map[string]interface{}{
                "id":              id,
                "seller":          ifNullString(seller, "无"),
                "buyers":          ifNullString(buyers, "无"),
                "group_id":        ifNullString(group_id, "无"),
                "item_name":       ifNullString(item_name, "无"),
                "description":     ifNullString(description, "无"),
                "price":           ifNullFloat64(price, 0.0),
                "quantity":        ifNullInt64(quantity, 0),
                "image_file_name": ifNullString(image_file_name, "无"),
            }
            tradeItems = append(tradeItems, item)
        }

        // 查询 users 表
        rows, err = db.Query("SELECT id, username, name, ai_group, star_journal, invite_code, used_invite_code FROM users")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()

        var users []map[string]interface{}
        for rows.Next() {
            var id int
            var username, name, ai_group, star_journal, invite_code, used_invite_code sql.NullString

            err = rows.Scan(&id, &username, &name, &ai_group, &star_journal, &invite_code, &used_invite_code)
            if err != nil {
                log.Fatal(err)
            }

            user := map[string]interface{}{
                "id":              id,
                "username":        username.String,
                "name":            name.String,
                "ai_group":        ai_group.String,
                "star_journal":    star_journal.String,
                "invite_code":     invite_code.String,
                "used_invite_code": used_invite_code.String,
            }
            users = append(users, user)
        }

        // 查询 message_board 表
        rows, err = db.Query("SELECT id, username, content, avatar_path, created_at FROM message_board")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()

        var messages []map[string]interface{}
        for rows.Next() {
            var id int
            var username, content, avatar_path sql.NullString
            var created_at sql.NullString

            err = rows.Scan(&id, &username, &content, &avatar_path, &created_at)
            if err != nil {
                log.Fatal(err)
            }

            message := map[string]interface{}{
                "id":          id,
                "username":    username.String,
                "content":     content.String,
                "avatar_path": avatar_path.String,
                "created_at":  created_at.String,
            }
            messages = append(messages, message)
        }

        // 传递所有数据给HTML模板
        c.HTML(http.StatusOK, "web.html", gin.H{
            "tradeItems": tradeItems,
            "users":      users,
            "messages":   messages,
        })
    })

    r.POST("/trade_items/update/:id", func(c *gin.Context) {
        id := c.Param("id")
        var data map[string]interface{}
        if err := c.BindJSON(&data); err != nil {
            log.Fatal(err)
        }

        _, err := db.Exec("UPDATE trade_items SET seller = ?, buyers = ?, group_id = ?, item_name = ?, description = ?, price = ?, quantity = ?, image_file_name = ? WHERE id = ?", data["seller"], data["buyers"], data["group_id"], data["item_name"], data["description"], data["price"], data["quantity"], data["image_file_name"], id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })

    r.DELETE("/trade_items/delete/:id", func(c *gin.Context) {
        id := c.Param("id")
        _, err := db.Exec("DELETE FROM trade_items WHERE id = ?", id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })

    r.POST("/users/update/:id", func(c *gin.Context) {
        id := c.Param("id")
        var data map[string]interface{}
        if err := c.BindJSON(&data); err != nil {
            log.Fatal(err)
        }

        _, err := db.Exec("UPDATE users SET username = ?, name = ?, ai_group = ?, star_journal = ?, invite_code = ?, used_invite_code = ? WHERE id = ?", data["username"], data["name"], data["ai_group"], data["star_journal"], data["invite_code"], data["used_invite_code"], id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })

    r.DELETE("/users/delete/:id", func(c *gin.Context) {
        id := c.Param("id")
        _, err := db.Exec("DELETE FROM users WHERE id = ?", id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })

    r.POST("/messages/update/:id", func(c *gin.Context) {
        id := c.Param("id")
        var data map[string]interface{}
        if err := c.BindJSON(&data); err != nil {
            log.Fatal(err)
        }

        _, err := db.Exec("UPDATE message_board SET username = ?, content = ?, avatar_path = ? WHERE id = ?", data["username"], data["content"], data["avatar_path"], id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })

    r.DELETE("/messages/delete/:id", func(c *gin.Context) {
        id := c.Param("id")
        _, err := db.Exec("DELETE FROM message_board WHERE id = ?", id)
        if err != nil {
            log.Fatal(err)
        }
        c.Status(http.StatusOK)
    })
    
    r.GET("/jie/manage", func(c *gin.Context) {
        // 查询符合条件的段位信息
        rankQuery := "SELECT Rank FROM RankPrices WHERE RankOrder BETWEEN 333 AND 498"
        rankRows, err := db.Query(rankQuery)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve rank prices"})
            return
        }
        defer rankRows.Close()
    
        var ranks []string
        for rankRows.Next() {
            var rank string
            if err := rankRows.Scan(&rank); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan rank prices"})
                return
            }
            ranks = append(ranks, rank)
        }
        ranksJSON, err := json.Marshal(ranks)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize ranks"})
            return
        }
    
        // 查询订单追踪信息
        rows, err := db.Query("SELECT StarredUser, WaitingFor, OrderType, Rank, Position, Direction, GroupChatActive, Active FROM RankTrackings")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve data"})
            return
        }
        defer rows.Close()
    
        var trackings []RankTracking
        for rows.Next() {
            var tracking RankTracking
            if err := rows.Scan(&tracking.StarredUser, &tracking.WaitingFor, &tracking.OrderType, &tracking.Rank, &tracking.Position, &tracking.Direction, &tracking.GroupChatActive, &tracking.Active); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan data"})
                return
            }
            trackings = append(trackings, tracking)
        }
    
        // 从数据库查询好友列表（替换旧的 self.Friends() 方法）
        friendRows, err := db.Query("SELECT nickName FROM friends") // 可根据需要添加 COALESCE(nickName, userName)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve friends from database"})
            return
        }
        defer friendRows.Close()
    
        var friendNames []string
        for friendRows.Next() {
            var nickName string
            if err := friendRows.Scan(&nickName); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan friend records"})
                return
            }
            friendNames = append(friendNames, nickName)
        }
    
        // 处理可能的 NULL 值（如果数据库允许 nickName 为空）
        // 可选：将空昵称替换为 userName
        // 需要在查询时 SELECT COALESCE(nickName, userName) FROM friends
    
        friendsJSON, err := json.Marshal(friendNames)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize friends"})
            return
        }
    
        // 将所有数据传递到模板
        c.HTML(http.StatusOK, "jie.html", gin.H{
            "trackings": trackings,
            "friends":   template.JS(friendsJSON),
            "ranks":     template.JS(ranksJSON),
            "orders":    orders,
        })
    })
    
    r.POST("/validateRank", func(c *gin.Context) {
        var request struct {
            OrderType   string `json:"orderType"`
            Rank        string `json:"rank"`
            Position    string `json:"position"`
            Direction   string `json:"direction"`
            StarredUser string `json:"friend"` // 修改这里将JSON的friend映射到结构体的StarredUser字段
        }
    
        rawData, err := io.ReadAll(c.Request.Body)
        if err != nil {
            log.Printf("Error reading raw data: %s", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Cannot read request data"})
            return
        }
        log.Printf("Received raw data: %s", string(rawData))
    
        if err := json.Unmarshal(rawData, &request); err != nil {
            log.Printf("Error binding JSON: %s", err)
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data", "detail": err.Error()})
            return
        }
    
        // 数据库操作：首先检查 StarredUser 是否存在
        var exists int
        if err := db.QueryRow("SELECT COUNT(*) FROM RankTrackings WHERE StarredUser = ?", request.StarredUser).Scan(&exists); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database", "detail": err.Error()})
            return
        }
    
        if exists == 0 {
            // 如果不存在，则插入新记录
            if _, err := db.Exec("INSERT INTO RankTrackings (StarredUser, OrderType, Rank, Position, Direction, GroupChatActive, Active) VALUES (?, ?, ?, ?, ?, true, false)",
                request.StarredUser, request.OrderType, request.Rank, request.Position, request.Direction); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update database", "detail": err.Error()})
                return
            }
        } else {
            // 如果存在，则更新记录
            if _, err := db.Exec("UPDATE RankTrackings SET OrderType = ?, Rank = ?, Position = ?, Direction = ?, GroupChatActive = true, Active = false WHERE StarredUser = ?",
                request.OrderType, request.Rank, request.Position, request.Direction, request.StarredUser); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update database", "detail": err.Error()})
                return
            }
        }
    
        // 成功处理请求
        c.JSON(http.StatusOK, gin.H{"message": "Order processed successfully"})
    })
    // 添加订单切换状态的路由
    r.POST("/validateRank/stopOrder", func(c *gin.Context) {
        var req struct {
            StarredUser string `json:"starredUser"`
            Active      bool   `json:"active"` 
        }
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
            return
        }

        // 更新数据库中的订单状态
        _, err := db.Exec("UPDATE RankTrackings SET GroupChatActive = ? WHERE StarredUser = ?", req.Active, req.StarredUser)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to toggle order status"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": true, "message": "Order status toggled successfully"})
    })
    // 添加订单切换状态的路由
    r.POST("/validateRank/startOrder", func(c *gin.Context) {
        var req struct {
            StarredUser string `json:"starredUser"`
            Active      bool   `json:"active"` 
        }
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
            return
        }
        log.Printf("Attempting to update order status for StarredUser: %s with Active: %v", req.StarredUser, req.Active)
        // 更新数据库中的订单状态
        _, err := db.Exec("UPDATE RankTrackings SET GroupChatActive = ? WHERE StarredUser = ?", req.Active, req.StarredUser)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to toggle order status"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"success": true, "message": "Order status toggled successfully"})
    })
    r.POST("/validateRank/deleteOrder", func(c *gin.Context) {
        var req struct {
            StarredUser string `json:"starredUser"`
            OrderType   string `json:"orderType"`
            Rank        string `json:"rank"`
            Position    string `json:"position"`
            Direction   string `json:"direction"`
        }
    
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
            return
        }
    
        // 执行删除操作
        _, err := db.Exec(`
            DELETE FROM RankTrackings
            WHERE StarredUser = ? AND OrderType = ? AND Rank = ? AND Position = ? AND Direction = ?`,
            req.StarredUser, req.OrderType, req.Rank, req.Position, req.Direction)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete order"})
            return
        }
    
        c.JSON(http.StatusOK, gin.H{"success": true, "message": "Order successfully deleted"})
    })
    
    // 处理订单停止
    r.POST("/validateRank/stopFlexibleOrder", func(c *gin.Context) {
        var requestData struct {
            OrderDetails []string `json:"orderDetails"`
        }

        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
            return
        }

        mu.Lock()
        for i := range orders {
            if equal(orders[i].OrderDetails, requestData.OrderDetails) {
                orders[i].Stop = true
                c.JSON(http.StatusOK, gin.H{"message": "Order stopped successfully"})
                mu.Unlock()
                return
            }
        }
        mu.Unlock()
        c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
    })
    // 处理订单开始
    r.POST("/validateRank/startFlexibleOrder", func(c *gin.Context) {
        var requestData struct {
            OrderDetails []string `json:"orderDetails"`
        }

        if err := c.BindJSON(&requestData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
            return
        }

        mu.Lock()
        for i := range orders {
            if equal(orders[i].OrderDetails, requestData.OrderDetails) {
                orders[i].Stop = false
                c.JSON(http.StatusOK, gin.H{"message": "Order started successfully"})
                mu.Unlock()
                return
            }
        }
        mu.Unlock()
        c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
    })
    // 处理订单更新
    r.POST("/validateRank/updateFlexibleOrder", func(c *gin.Context) {
        var updateData struct {
            OldOrderDetails []string `json:"oldOrderDetails"`
            NewOrderDetails []string `json:"newOrderDetails"`
            SelfOrder       bool     `json:"selfOrder"`
            Friend          string   `json:"friend"`
            // 移除 RestrictedOrderDetails 字段
        }

        if err := c.BindJSON(&updateData); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
            return
        }

        mu.Lock()
        for i := range orders {
            if equal(orders[i].OrderDetails, updateData.OldOrderDetails) {
                orders[i].OrderDetails = updateData.NewOrderDetails
                orders[i].SelfOrder = updateData.SelfOrder
                orders[i].Friend = updateData.Friend
                // 不更新 RestrictedOrderDetails
                c.JSON(http.StatusOK, gin.H{"message": "Order updated successfully"})
                mu.Unlock()
                return
            }
        }
        mu.Unlock()
        c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
    })

    r.GET("/message/manage", func(c *gin.Context) {
        // 从数据库查询群组列表
        rows, err := db.Query(`
            SELECT 
                userName,
                COALESCE(NULLIF(nickName, ''), userName) AS displayName 
            FROM groups
        `)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "error": "Failed to retrieve groups from database",
            })
            return
        }
        defer rows.Close()
    
        var groupList []map[string]string
        for rows.Next() {
            var (
                userName string
                nickName string
            )
            if err := rows.Scan(&userName, &nickName); err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{
                    "error": "Failed to scan group record: " + err.Error(),
                })
                return
            }
            groupList = append(groupList, map[string]string{
                "id":   userName,  // 使用 userName 作为唯一标识
                "name": nickName,   // 显示处理过的名称（优先 nickName，空值时用 userName）
            })
        }
    
        // 检查遍历过程中是否出错
        if err := rows.Err(); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "error": "Group data iteration error: " + err.Error(),
            })
            return
        }
    
        c.HTML(http.StatusOK, "message_manage.html", gin.H{
            "groups": groupList,
        })
    })

    r.POST("/api/new_task_alert", func(c *gin.Context) {
        task := Task{
            ID:     fmt.Sprintf("%d", time.Now().UnixNano()),
            Status: 1,
        }
        tasks = append(tasks, task)
        sendTextMessage(fmt.Sprintf("定时任务 %s 正在新建，请发送需要定时发送的图片和文本", task.ID), "Moki-Flanke")
        c.JSON(http.StatusOK, gin.H{"message": "提醒已发送", "id": task.ID})
    })

    r.POST("/api/save_task", func(c *gin.Context) {
        var input struct {
            ID       string   `json:"id"`
            Interval int      `json:"interval"`
            Groups   []string `json:"groups"`
        }
        if err := c.ShouldBindJSON(&input); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        var task *Task
        for i := range tasks {
            if tasks[i].ID == input.ID {
                task = &tasks[i]
                break
            }
        }

        if task == nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "找不到指定的任务"})
            return
        }

        if task.Status != 1 {
            c.JSON(http.StatusBadRequest, gin.H{"error": "当前没有可以保存的任务"})
            return
        }

        task.Interval = input.Interval
        task.GroupIDs = input.Groups
        task.Status = 2 // 将状态设置为已完成
        saveTaskToFile(*task)
        c.JSON(http.StatusOK, gin.H{"message": "任务已保存"})
    })
    r.DELETE("/api/delete_task", func(c *gin.Context) {
        var input struct {
            ID string `json:"id"`
        }
        if err := c.ShouldBindJSON(&input); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        for i, task := range tasks {
            if task.ID == input.ID {
                tasks = append(tasks[:i], tasks[i+1:]...)
                os.Remove(fmt.Sprintf("./tasks/%s.json", task.ID)) // 删除任务文件
                c.JSON(http.StatusOK, gin.H{"message": "任务已删除"})
                return
            }
        }
        c.JSON(http.StatusBadRequest, gin.H{"error": "找不到指定的任务"})
    })

    r.PUT("/api/update_task", func(c *gin.Context) {
        var input struct {
            ID       string `json:"id"`
            Interval int    `json:"interval"`
        }
        if err := c.ShouldBindJSON(&input); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        for i, task := range tasks {
            if task.ID == input.ID {
                tasks[i].Interval = input.Interval
                saveTaskToFile(tasks[i])
                c.JSON(http.StatusOK, gin.H{"message": "任务已更新"})
                return
            }
        }
        c.JSON(http.StatusBadRequest, gin.H{"error": "找不到指定的任务"})
    })
    // 获取当前定时任务列表的API
    r.GET("/api/tasks", func(c *gin.Context) {
        c.JSON(http.StatusOK, tasks)
    })

	r.Run(":6688")
}
func extractOrders(rows *sql.Rows, orders *[]Order) error {
    defer rows.Close()
    for rows.Next() {
        var order Order
        if err := rows.Scan(
            &order.ID, &order.GroupID, &order.GroupName, &order.GroupUserNickName, 
            &order.WeChatUser, &order.IsActive, &order.IsCompleted, &order.Msg, 
            &order.GameID, &order.Stars, &order.StarCost, &order.OrderType, 
            &order.CreatedAt, &order.LastMessageTime, &order.FinalRank, &order.WeChatUsername); err != nil {
            return err // 处理错误
        }
        *orders = append(*orders, order)
    }
    return nil
}


func AIMessages(Msg Data, Port int) {

    return
}
func handleMessages(data Data) {
    if !strings.HasSuffix(data.UserName, "@chatroom") {
        handlePrivateMessage(data)
        return
    }

    // 1. 验证外部群身份
    externalGroups.RLock()
    isExternal := externalGroups.groups[data.UserName]
    externalGroups.RUnlock()

    if !isExternal {
        handleGroupMessage(data)
        return
    }

    // 2. 获取必要字段
    roomNick := data.BytesExtra.RoomNick
    content := strings.TrimSpace(data.StrContent)
    if roomNick == "" || content == "" {
        return
    }

    // 3. 计算时间窗口（10分钟）
    currentWindow := time.Now().Unix() / 600
    contentHash := md5.Sum([]byte(content))

    detectionTarget.Lock()
    defer detectionTarget.Unlock()

    // 4. 新时间窗口处理
    if currentWindow != detectionTarget.window {
        // 保存上一个窗口的最终状态（如果不是首次运行）
        if detectionTarget.window != 0 {
            // 确定上一个窗口的状态
            switch {
            case detectionTarget.count > 10:
                previousWindowState = "拥挤"
            case detectionTarget.count > 5:
                previousWindowState = "繁忙"
            default:
                previousWindowState = "空闲"
            }
            
            log.Printf("\033[35m[窗口结束] 窗口:%d 最终状态:%s\033[0m",
                detectionTarget.window, previousWindowState)
        }
        
        // 重置检测目标
        detectionTarget.groupKey = data.UserName
        detectionTarget.roomNick = roomNick
        detectionTarget.contentHash = contentHash
        detectionTarget.window = currentWindow
        detectionTarget.count = 1
        
        log.Printf("\033[36m[新检测窗口] 窗口:%d 目标群:%s 用户:%s 内容摘要:%x\033[0m",
            currentWindow, data.UserName, roomNick, contentHash)
        handleGroupMessage(data)
        return
    }

    // 5. 相同窗口内检测
    if data.UserName != detectionTarget.groupKey ||
        roomNick != detectionTarget.roomNick ||
        contentHash != detectionTarget.contentHash {
        return
    }

    // 6. 计数更新
    detectionTarget.count++
    currentCount := detectionTarget.count

    // 7. 状态判断
    var status string
    switch {
    case currentCount > 10:
        status = "拥挤"
    case currentCount > 5:
        status = "繁忙"
    default:
        status = "空闲"
    }

    // 8. 日志输出
    log.Printf(
        "\033[34m[监控状态] 窗口:%d\033[0m\n"+
            "├─ 目标群组: %s\n"+
            "├─ 监控用户: %s\n"+
            "├─ 内容摘要: %x\n"+
            "├─ 累计消息: %d\n"+
            "└─ 当前状态: \033[31m%s\033[0m",
        currentWindow,
        detectionTarget.groupKey,
        detectionTarget.roomNick,
        detectionTarget.contentHash,
        currentCount,
        status,
    )

    handleGroupMessage(data)
}

func initGroupMonitor(db *sql.DB) {
	// 立即加载一次
	refreshExternalGroups(db)
	
	// 每小时刷新一次群列表
	go func() {
		for {
			time.Sleep(1 * time.Hour)
			refreshExternalGroups(db)
		}
	}()

}

// 刷新外部群列表
func refreshExternalGroups(db *sql.DB) {
	// 从数据库获取外部群列表的逻辑（同forwardMessageToAllGroupswaibu）
	var eventText string
	err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 3 AND event_title = '外部发单群'").Scan(&eventText)
	if err != nil {
		log.Printf("刷新外部群列表失败: %v", err)
		return
	}

	newGroups := make(map[string]bool)
	for _, nickname := range strings.Split(eventText, "||") {
		trimmed := strings.TrimSpace(nickname)
		if trimmed == "" {
			continue
		}

		var userName string
		err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", trimmed).Scan(&userName)
		if err == nil {
			newGroups[userName] = true
		}
	}

	externalGroups.Lock()
	externalGroups.groups = newGroups
	externalGroups.Unlock()
}

func handleGroupMessage(msgData Data) {
	var msg struct {
        Content      string
        FromUserName string
    }

    var sender struct {
        NickName string
        UserName string
    }

    // 将 Msg 中的字段赋值给 msg 和 sender 结构体
    msg.Content = msgData.StrContent           
    msg.FromUserName = msgData.UserName    
	groupName := msgData.NickName      

    sender.NickName = msgData.BytesExtra.NickName  
    sender.UserName = msgData.BytesExtra.UserName  
    // 检查是否符合特定条件的群聊消息
    if strings.HasPrefix(msgData.NickName, "今天你早起了吗") && 
        (strings.Contains(msgData.StrContent, "[太阳]") || strings.Contains(msgData.StrContent, "[月亮]") || strings.Contains(msgData.StrContent, "一分钟知天下事")) && 
        !strings.Contains(msgData.StrContent, "未及时打卡") && 
        !strings.Contains(msgData.StrContent, "菜单") {

        // 从数据库获取附加文本
        var additionalText string
        err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 9 AND event_title = '工作室的广告'").Scan(&additionalText)
        if err != nil {
            fmt.Printf("从数据库获取附加文本失败: %s\n", err)
            return
        }

        // 将原始内容和附加文本合并
        fullContent := msgData.StrContent + "\n" + additionalText

        // 转发合并后的消息到所有群，除了来源群
        forwardMessageToAllGroups(db, fullContent)
    }
	groupState := GetGroupState(msgData.UserName)
	if strings.HasPrefix(msgData.StrContent, "#完单") {
		// 重置当前群组的订单模式状态
		groupState.IsOrderMode = false
		groupState.IsOrderMode2 = false
		groupState.IsOrderMode3 = false
		groupState.IsOrderMode4 = false

		// 关闭桥梁
		closeBridge(msg.FromUserName, sender.NickName)

		thankYouMessage := fmt.Sprintf("感谢老板给我梦乐的大大大大力支持！那么下次有需要再呼我哟！\n====点单结束====")
        sendTextMessage(thankYouMessage, msgData.UserName)

		return // 防止进一步处理
	}
	// 如果消息内容是开启订单模式的命令
	if msg.Content == "来个车队" || msg.Content == "#来个车队"{
		closeBridge(msg.FromUserName, sender.NickName)
		groupState.IsOrderMode = true
		groupState.IsOrderMode2 = false
		groupState.IsOrderMode3 = false
		groupState.IsOrderMode4 = false
		sendTextMessage(fmt.Sprintf("====点单开始====\n哟呼！我梦乐来咯！告诉我你具体的段位和位置吧！像这样：#微信星耀53星法师"), msg.FromUserName)
		// 发送图片
		err := sendImage(orderModeImage, msg.FromUserName)
		if err != nil {
			fmt.Printf("发送图片失败: %v\n", err)
		}
		return
	}
	
	if msg.Content == "来个陪玩" || msg.Content == "#来个陪玩" {
		closeBridge(msg.FromUserName, sender.NickName)
		groupState.IsOrderMode = false
		groupState.IsOrderMode2 = true
		groupState.IsOrderMode3 = false
		groupState.IsOrderMode4 = false
		sendTextMessage(fmt.Sprintf("====点单开始====\n哟呼！我梦乐来咯！告诉我你的陪玩需求，像这样：#技术（娱乐陪），打野，声音磁性，微信王者9星"), msg.FromUserName)
		err := sendImage(orderModeImage, msg.FromUserName)
		if err != nil {
			fmt.Printf("发送图片失败: %v\n", err)
		}
		closeBridge(msg.FromUserName, sender.NickName)
		return
	}
	
	if msg.Content == "来个小姐姐" || msg.Content == "#来个小姐姐" {
		closeBridge(msg.FromUserName, sender.NickName)
		groupState.IsOrderMode = false
		groupState.IsOrderMode2 = false
		groupState.IsOrderMode3 = true
		groupState.IsOrderMode4 = false
		sendTextMessage(fmt.Sprintf("====点单开始====\n哟呼！我梦乐来咯！告诉我你的小姐姐陪玩需求，像这样：#小姐姐，辅助，声音好听，微信王者9星"), msg.FromUserName)
		// 发送图片
		err := sendImage(orderModeImage, msg.FromUserName)
		if err != nil {
			fmt.Printf("发送图片失败: %v\n", err)
		}
		return
	}

	if msg.Content == "来个代练" || msg.Content == "#来个代练" {
		closeBridge(msg.FromUserName, sender.NickName)
		groupState.IsOrderMode = false
		groupState.IsOrderMode2 = false
		groupState.IsOrderMode3 = false
		groupState.IsOrderMode4 = true
		sendTextMessage(fmt.Sprintf("====点单开始====\n哟呼！我梦乐来咯！告诉我你的代打需求，像这样：#排位（巅峰，国标），微信王者9星，是否指定"), msg.FromUserName)
		// 发送图片
		err := sendImage(orderModeImage, msg.FromUserName)
		if err != nil {
			fmt.Printf("发送图片失败: %v\n", err)
		}
		return
	}
    rechargeCodeMatch := regexp.MustCompile(`兑换码：(\d+)|\b\d{18,19}\b`).FindStringSubmatch(msg.Content)
    var code string
    var stars int
    if len(rechargeCodeMatch) > 1 {
        if rechargeCodeMatch[1] != "" {
            code = rechargeCodeMatch[1] // 匹配“兑换码：”后的数字
        } else if rechargeCodeMatch[0] != "" {
            code = rechargeCodeMatch[0] // 匹配纯18位或19位数字
        }
        
        amount, err := redeemRechargeCode(db, code) // 兑换码兑换
        if err != nil {
            return
        }

        // 使用群昵称和发送者昵称更新星卷数量
        stars, _ = updateStarsCount(db, groupName, sender.NickName, amount)
        xj := queryMemberStars(db, groupName, sender.NickName) // 查询星卷数量
        sendTextMessage(fmt.Sprintf("您成功兑换了 %d 星卷！您当前的星卷数量为：%d", stars, int(xj)), msg.FromUserName)

        // 查找与发送者相关联的桥接对象
        bridge := findBridge(msg.FromUserName, sender.NickName)
        if bridge != nil && bridge.IsActive {
            // 如果订单类型是代练，星卷数翻倍
            if bridge.OrderType == "代练" && !strings.Contains(bridge.Msg, "巅峰") {
                xj *= 2 
            }
            var initialRanks []string
            // 从bridge.Msg中提取最大升级次数
            re := regexp.MustCompile(",最多打(\\d+)(♥|净胜)")
            matches := re.FindStringSubmatch(bridge.Msg)
            var maxUpgrades int
            if len(matches) > 1 {
                maxUpgrades, _ = strconv.Atoi(matches[1])
            }        
            ranksCosts, err := getAllRanksAndCosts(db)
            if err != nil {
                fmt.Printf("Error getting ranks and prices: %v\n", err)
                return
            }
            
            // 对ranksCosts按照段位长度进行排序
            var ranks []string
            for _, rankCost := range ranksCosts {
                ranks = append(ranks, rankCost[0])  // 添加段位名称
            }

            sort.Slice(ranks, func(i, j int) bool {
                return len(ranks[i]) > len(ranks[j])
            })

            // 解析 bridge.Msg 来获取匹配的段位
            var matchedRanks []string
            input := bridge.Msg
            for _, rank := range ranks {
                rankOccurrences := strings.Count(input, rank)
                for i := 0; i < rankOccurrences; i++ {
                    matchedRanks = append(matchedRanks, rank)
                    input = strings.Replace(input, rank, "", 1)
                }
            }

            initialRanks = matchedRanks
            fmt.Printf("初始段位: %v\n", initialRanks)
            finalRanks, upgrades, err := calculateMaxUpgradesAndRank(db, initialRanks, int(xj))
            if err != nil {
                fmt.Printf("无法计算升级: %v\n", err)
                return
            }
            fmt.Printf("升级星数: %v\n", upgrades)
            fmt.Printf("升级后的段位: %v\n", finalRanks)
            // 向桥接中记录的微信用户发送续单信息
            weChatUser := bridge.WeChatUser
            weChatUserName, err := findUserNameByNickName(weChatUser)
            if err != nil {
                fmt.Printf("根据昵称查找用户失败: %v\n", err)
                return
            }
            actualUpgrades := upgrades - maxUpgrades
            sendTextMessage(fmt.Sprintf("老板额外续单 %d 星，总共打 %d 星，继续打", int(actualUpgrades), upgrades), weChatUserName)
        }
        return
    }
    // 处理 "我的星卷" 命令
    if strings.Contains(msg.Content, "我的星卷") {
        totalStars := queryMemberStars(db, groupName, sender.NickName) // 使用用户昵称查询星卷数
        sendTextMessage(fmt.Sprintf("%s，你当前的星卷总数为: %d", sender.NickName, totalStars), msg.FromUserName)
        return
    }
	// 处理订单模式下的其他命令
	if (groupState.IsOrderMode || groupState.IsOrderMode2 || groupState.IsOrderMode3 || groupState.IsOrderMode4) && strings.HasPrefix(msg.Content, "#") || strings.HasPrefix(msg.Content, "＃"){
		msg.Content = strings.Replace(msg.Content, "＃", "#", -1)

		// 检查处理后的消息内容是否以半角井号开头
		if strings.HasPrefix(msg.Content, "#") {
			var mode string
			if groupState.IsOrderMode {
				mode = "车队"
			} else if groupState.IsOrderMode2 {
				mode = "陪玩"
			} else if groupState.IsOrderMode3 {
				mode = "小姐姐"
			} else if groupState.IsOrderMode4 {
				mode = "代练"
			}
		
			bridge := findBridge(msg.FromUserName, sender.NickName)
			if bridge == nil && !isInternalOrderMode {
				// 获取发送者的昵称
				senderNickName := sender.NickName
				switch mode {
				case "车队":
					if strings.Contains(msg.Content,"王者") && !strings.ContainsAny(msg.Content,"0123456789") {
						sendTextMessage(fmt.Sprintf("您的输入有误，请输入王者的具体星数以确定安排"), msg.FromUserName)
						return
					}

					stars := queryMemberStars(db, groupName, senderNickName)
					input := strings.TrimPrefix(msg.Content, "#")
					ranksAndPrices, err := getRanksAndPrices(db)
					if err != nil {
						fmt.Printf("Error getting ranks and prices: %v\n", err)
						return
					}

					// 对ranksAndPrices按照段位长度进行排序
					var ranks []string
					for rank := range ranksAndPrices {
						ranks = append(ranks, rank)
					}
					sort.Slice(ranks, func(i, j int) bool {
						return len(ranks[i]) > len(ranks[j])
					})
					var matchedRanks []string
					totalPrice := 0
					for _, rank := range ranks {
						rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
						for i := 0; i < rankOccurrences; i++ {
							matchedRanks = append(matchedRanks, rank)
							totalPrice += ranksAndPrices[rank]
							input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
						}
					}
					targetRanks := []string{"铂金", "钻石", "星耀"}
					roleCategories := []string{
						"打野", "野", "刺客",
						"法师", "中路", "法", "中",
						"边路", "对抗", "边",
						"射手", "发育", "射",
						"辅助", "游走", "辅",
					}
					matchedRanksString := strings.Join(matchedRanks, " ") // 将匹配的段位列表转换成单个字符串
					
					for _, target := range targetRanks {
						for _, role := range roleCategories {
							if strings.Contains(msg.Content, target) && !strings.Contains(matchedRanksString, target) && !strings.Contains(msg.Content, role) {
								sendTextMessage(fmt.Sprintf("您的输入有误，请输入具体段位位置，不用加空格，如#星耀51星法师"), msg.FromUserName)
								return // End function execution if a required rank is not matched
							}
						}
					}
					
					// 检查是否有匹配的段位
					if len(matchedRanks) == 0 {
						sendTextMessage(fmt.Sprintf("请输入具体段位星数，以确定安排"), msg.FromUserName)
						return // 结束函数执行
					}
					// 计算星卷消耗
					maxUpgrades, maxRankReached, remainingStars, err := calculateMaxRank(db, stars, matchedRanks, mode)
					if err != nil {
						fmt.Printf("Error calculating max rank: %v\n", err)
						return
					}
					if maxUpgrades == 0 {
						message := fmt.Sprintf("你的星卷不足，请扫码下方二维码联系群主获取更多星卷！当前星卷为%d", remainingStars)
						sendTextMessage(message, msg.FromUserName)                     
						err := sendImage(orderModeImage2, msg.FromUserName)
						if err != nil {
							fmt.Printf("发送图片失败: %v\n", err)
						}
						return
					}             
					// 如果匹配到多个段位，则应用多人优惠
					if len(matchedRanks) > 1 {
						totalPrice -= 1
					}
					content := input
					if len(matchedRanks) > 0 {
						content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + strconv.Itoa(totalPrice)
					} else {
						content += "，群价"
					}
					content += ",最多打" + strconv.Itoa(maxUpgrades) + "净胜"
					content += "，复制信息发我，#秒开车队来"

					forwardMessageToAllGroupswaibu(db, content)
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0)
					sendTextMessage(fmt.Sprintf(fmt.Sprintf("好勒！现在给你找大腿了！乖乖别动哈！你目前能达到的最高段位为%s", maxRankReached)), msg.FromUserName)
					return
				case "陪玩":
					content := strings.TrimPrefix(msg.Content, "#") + " 群价" + "，复制信息发我，#技术娱乐陪接"
					forwardMessageToAllGroupspeiwan(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0) // 对于陪玩或代练，星卷消耗为0
					sendTextMessage(fmt.Sprintf("好勒！现在给你找陪玩了！乖乖别动哈！"), msg.FromUserName)
					return
				case "小姐姐":                       
					content := strings.TrimPrefix(msg.Content, "#") + " 群价" + "，复制信息发我，#小姐姐接"
					forwardMessageToAllGroupsxjj(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0) // 对于陪玩或代练，星卷消耗为0
					sendTextMessage(fmt.Sprintf("好勒！现在给你找小姐姐了！乖乖别动哈！"), msg.FromUserName)
					return
				case "代练":
					if strings.Contains(msg.Content,"王者") && !strings.ContainsAny(msg.Content,"0123456789") {
						sendTextMessage(fmt.Sprintf("您的输入有误，请输入王者的具体星数以确定安排"), msg.FromUserName)
						return
					}
					stars := queryMemberStars(db, groupName, senderNickName)
					input := strings.TrimPrefix(msg.Content, "#")
					ranksAndPrices, err := getRanksAndPrices(db)
					if err != nil {
						fmt.Printf("Error getting ranks and prices: %v\n", err)
						return
					}
					matchedPeak, nearestPeak := parsePeakRank(input)
					if matchedPeak != "" {
						// 更新输入，移除原始的巅峰段位描述
						updatedInput := strings.Replace(input, matchedPeak, "", 1)
						
						// 调用计算函数，传入最接近的巅峰段位
						proceedWithCalculation(db, nearestPeak, stars, updatedInput, matchedPeak, groupName, senderNickName, sender.UserName)
						return
					}                                  
					// 对ranksAndPrices按照段位长度进行排序
					var ranks []string
					for rank := range ranksAndPrices {
						ranks = append(ranks, rank)
					}
					sort.Slice(ranks, func(i, j int) bool {
						return len(ranks[i]) > len(ranks[j])
					})
					var matchedRanks []string
					totalPrice := 0
					for _, rank := range ranks {
						rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
						for i := 0; i < rankOccurrences; i++ {
							matchedRanks = append(matchedRanks, rank)
							totalPrice += ranksAndPrices[rank]
							input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
						}
					}
					targetRanks := []string{"铂金", "钻石", "星耀"}
					roleCategories := []string{
						"打野", "野", "刺客",
						"法师", "中路", "法", "中",
						"边路", "对抗", "边",
						"射手", "发育", "射",
						"辅助", "游走", "辅",
					}
					matchedRanksString := strings.Join(matchedRanks, " ") // 将匹配的段位列表转换成单个字符串
					
					for _, target := range targetRanks {
						for _, role := range roleCategories {
							if strings.Contains(msg.Content, target) && !strings.Contains(matchedRanksString, target) && !strings.Contains(msg.Content, role) {
								sendTextMessage(fmt.Sprintf("您的输入有误，请输入具体段位位置，不用加空格，如#星耀51星法师"), msg.FromUserName)
								return // End function execution if a required rank is not matched
							}
						}
					}
					
					// 检查是否有匹配的段位
					if len(matchedRanks) == 0 {
						sendTextMessage(fmt.Sprintf("请输入具体段位星数，以确定安排"), msg.FromUserName) 
						return // 结束函数执行
					}
					// 计算星卷消耗
					maxUpgrades, maxRankReached, remainingStars, err := calculateMaxRank(db, stars, matchedRanks, mode)
					if err != nil {
						fmt.Printf("Error calculating max rank: %v\n", err)
						return
					}
					if maxUpgrades == 0 {
						message := fmt.Sprintf("你的星卷不足，请扫码下方二维码联系群主获取更多星卷！当前星卷为%d", remainingStars)
						sendTextMessage(message, msg.FromUserName)                        
						err := sendImage(orderModeImage2, msg.FromUserName)
						if err != nil {
							fmt.Printf("发送图片失败: %v\n", err)
						}
						return
					}             
					// 如果匹配到多个段位，则应用多人优惠
					if len(matchedRanks) > 1 {
						totalPrice -= 1
					}
					content := input
					if len(matchedRanks) > 0 {
						// 假设 totalPrice 是一个整数
						adjustedPrice := float64(totalPrice) / 2.0 // 将 totalPrice 转为浮点数进行除法运算

						// 使用 fmt.Sprintf 格式化浮点数，保留一位小数
						formattedPrice := fmt.Sprintf("%.1f", adjustedPrice) // 将浮点数格式化为字符串，保留一位小数

						content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + formattedPrice
					} else {
						content += "，群价"
					}
					content += ",最多打" + strconv.Itoa(maxUpgrades) + "♥"
					content += "，复制信息发我，#通天代接"
					forwardMessageToAllGroupsdailian(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0)
					sendTextMessage(fmt.Sprintf(fmt.Sprintf("好勒！现在给你找通天代大佬了！乖乖别动哈！你目前能达到的最高段位为%s", maxRankReached)), msg.FromUserName)
					return
				}
			}else if bridge == nil && isInternalOrderMode {
				// 获取发送者的昵称
				senderNickName := sender.NickName
				switch mode {
				case "车队":
					if strings.Contains(msg.Content,"王者") && !strings.ContainsAny(msg.Content,"0123456789") {
						sendTextMessage(fmt.Sprintf("您的输入有误，请输入王者的具体星数以确定安排"), msg.FromUserName)
						return
					}
					stars := queryMemberStars(db, groupName, senderNickName)
					input := strings.TrimPrefix(msg.Content, "#")
					ranksAndPrices, err := getRanksAndPrices(db)
					if err != nil {
						fmt.Printf("Error getting ranks and prices: %v\n", err)
						return
					}

					// 对ranksAndPrices按照段位长度进行排序
					var ranks []string
					for rank := range ranksAndPrices {
						ranks = append(ranks, rank)
					}
					sort.Slice(ranks, func(i, j int) bool {
						return len(ranks[i]) > len(ranks[j])
					})
					var matchedRanks []string
					totalPrice := 0
					for _, rank := range ranks {
						rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
						for i := 0; i < rankOccurrences; i++ {
							matchedRanks = append(matchedRanks, rank)
							totalPrice += ranksAndPrices[rank]
							input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
						}
					}
					targetRanks := []string{"铂金", "钻石", "星耀"}
					roleCategories := []string{
						"打野", "野", "刺客",
						"法师", "中路", "法", "中",
						"边路", "对抗", "边",
						"射手", "发育", "射",
						"辅助", "游走", "辅",
					}
					matchedRanksString := strings.Join(matchedRanks, " ") // 将匹配的段位列表转换成单个字符串
					
					for _, target := range targetRanks {
						for _, role := range roleCategories {
							if strings.Contains(msg.Content, target) && !strings.Contains(matchedRanksString, target) && !strings.Contains(msg.Content, role) {
								sendTextMessage(fmt.Sprintf("您的输入有误，请输入具体段位位置，不用加空格，如#星耀51星法师"), msg.FromUserName)
								return // End function execution if a required rank is not matched
							}
						}
					}
					
					// 检查是否有匹配的段位
					if len(matchedRanks) == 0 {
						sendTextMessage(fmt.Sprintf("请输入具体段位星数，以确定安排"), msg.FromUserName) 
						return // 结束函数执行
					} 
					// 计算星卷消耗
					maxUpgrades, maxRankReached, remainingStars, err := calculateMaxRank(db, stars, matchedRanks, mode)
					if err != nil {
						fmt.Printf("Error calculating max rank: %v\n", err)
						return

					}
					if maxUpgrades == 0 {                        
						message := fmt.Sprintf("你的星卷不足，请扫码下方二维码联系群主获取更多星卷！当前星卷为%d", remainingStars)
						sendTextMessage(message, msg.FromUserName)                        
						err := sendImage(orderModeImage2, msg.FromUserName)
						if err != nil {
							fmt.Printf("发送图片失败: %v\n", err)
						}
						return
					}             
					// 如果匹配到多个段位，则应用多人优惠
					if len(matchedRanks) > 1 {
						totalPrice -= 1
					}
					content := input
					if len(matchedRanks) > 0 {
						content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + strconv.Itoa(totalPrice)
					} else {
						content += "，群价"
					}
					content += ",最多打" + strconv.Itoa(maxUpgrades) + "净胜"
					content += "，复制信息发我，#秒开车队来"

					forwardMessageToAllGroupsneibu(db, content)
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0)
					sendTextMessage(fmt.Sprintf(fmt.Sprintf("好勒！现在给你找大腿了！乖乖别动哈！你目前能达到的最高段位为%s", maxRankReached)), msg.FromUserName)
					return
				case "陪玩":
					content := strings.TrimPrefix(msg.Content, "#") + " 群价" + "，复制信息发我，#技术娱乐陪接"
					forwardMessageToAllGroupspeiwan(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0) // 对于陪玩或代练，星卷消耗为0
					sendTextMessage(fmt.Sprintf("好勒！现在给你找陪玩了！乖乖别动哈！"), msg.FromUserName)
					return
				case "小姐姐":
					content := strings.TrimPrefix(msg.Content, "#") + " 群价" + "，复制信息发我，#小姐姐接"
					forwardMessageToAllGroupsxjj(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0) // 对于陪玩或代练，星卷消耗为0
					sendTextMessage(fmt.Sprintf("好勒！现在给你找小姐姐了！乖乖别动哈！"), msg.FromUserName)
					return
				case "代练":
					if strings.Contains(msg.Content,"王者") && !strings.ContainsAny(msg.Content,"0123456789") {
						sendTextMessage(fmt.Sprintf("您的输入有误，请输入王者的具体星数以确定安排"), msg.FromUserName)
						return
					}
					stars := queryMemberStars(db, groupName, senderNickName)
					input := strings.TrimPrefix(msg.Content, "#")
					ranksAndPrices, err := getRanksAndPrices(db)
					if err != nil {
						fmt.Printf("Error getting ranks and prices: %v\n", err)
						return
					}
					matchedPeak, nearestPeak := parsePeakRank(input)
					if matchedPeak != "" {
						// 更新输入，移除原始的巅峰段位描述
						updatedInput := strings.Replace(input, matchedPeak, "", 1)
						
						// 调用计算函数，传入最接近的巅峰段位
						proceedWithCalculation(db, nearestPeak, stars, updatedInput, matchedPeak, groupName, senderNickName, sender.UserName)
						return
					}      
					// 对ranksAndPrices按照段位长度进行排序
					var ranks []string
					for rank := range ranksAndPrices {
						ranks = append(ranks, rank)
					}
					sort.Slice(ranks, func(i, j int) bool {
						return len(ranks[i]) > len(ranks[j])
					})
					var matchedRanks []string
					totalPrice := 0
					for _, rank := range ranks {
						rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
						for i := 0; i < rankOccurrences; i++ {
							matchedRanks = append(matchedRanks, rank)
							totalPrice += ranksAndPrices[rank]
							input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
						}
					}
					targetRanks := []string{"铂金", "钻石", "星耀"}
					roleCategories := []string{
						"打野", "野", "刺客",
						"法师", "中路", "法", "中",
						"边路", "对抗", "边",
						"射手", "发育", "射",
						"辅助", "游走", "辅",
					}
					matchedRanksString := strings.Join(matchedRanks, " ") // 将匹配的段位列表转换成单个字符串
					
					for _, target := range targetRanks {
						for _, role := range roleCategories {
							if strings.Contains(msg.Content, target) && !strings.Contains(matchedRanksString, target) && !strings.Contains(msg.Content, role) {
								sendTextMessage(fmt.Sprintf("您的输入有误，请输入具体段位位置，不用加空格，如#星耀51星法师"), msg.FromUserName)
								return // End function execution if a required rank is not matched
							}
						}
					}
					
					// 检查是否有匹配的段位
					if len(matchedRanks) == 0 {
						sendTextMessage(fmt.Sprintf("请输入具体段位星数，以确定安排"), msg.FromUserName) 
						return // 结束函数执行
					}
					// 计算星卷消耗
					maxUpgrades, maxRankReached, remainingStars, err := calculateMaxRank(db, stars, matchedRanks, mode)
					if err != nil {
						fmt.Printf("Error calculating max rank: %v\n", err)
						return
					}
					if maxUpgrades == 0 {
						message := fmt.Sprintf("你的星卷不足，请扫码下方二维码联系群主获取更多星卷！当前星卷为%d", remainingStars)
						sendTextMessage(message, msg.FromUserName)                        
						err := sendImage(orderModeImage2, msg.FromUserName)
						if err != nil {
							fmt.Printf("发送图片失败: %v\n", err)
						}
						return
					}             
					// 如果匹配到多个段位，则应用多人优惠
					if len(matchedRanks) > 1 {
						totalPrice -= 1
					}
					content := input
					if len(matchedRanks) > 0 {
						// 假设 totalPrice 是一个整数
						adjustedPrice := float64(totalPrice) / 2.0 // 将 totalPrice 转为浮点数进行除法运算

						// 使用 fmt.Sprintf 格式化浮点数，保留一位小数
						formattedPrice := fmt.Sprintf("%.1f", adjustedPrice) // 将浮点数格式化为字符串，保留一位小数

						content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + formattedPrice
					} else {
						content += "，群价"
					}
					content += ",最多打" + strconv.Itoa(maxUpgrades) + "♥"
					content += "，复制信息发我，#通天代接"
					forwardMessageToAllGroupsdailian(db, content) // 转发消息到所有群
					createBridge(msg.FromUserName, groupName, senderNickName, content, mode, 0)
					sendTextMessage(fmt.Sprintf("好勒！现在给你找通天代大佬了！乖乖别动哈！你目前能达到的最高段位为%s", maxRankReached), msg.FromUserName)
					return
				} 
			}else {
				handleBridgeConversation(db, msg.FromUserName, sender.NickName, msg.Content)
			}
		}
	}
    if currentTracking != nil && currentTracking.GroupChatActive && ((currentTracking.OrderType == "车队" && strings.Contains(msg.Content, "#秒开车队来")) ||
        (currentTracking.OrderType == "代练" && strings.Contains(msg.Content, "#通天代接")) ||
        (currentTracking.OrderType == "小姐姐" && strings.Contains(msg.Content, "#小姐姐接")) ||
        (currentTracking.OrderType == "陪玩" && strings.Contains(msg.Content, "#技术娱乐陪接"))) {
        if currentTracking.Position != "" && !positionMatches(msg.Content, currentTracking.Position) {
            fmt.Printf("位置不匹配，跳过处理: %s\n", currentTracking.Position)
            return // 位置不匹配则跳过处理
        }
        
        rankInMessage, err := extractRankFromMessage(msg.Content, db)
        if err != nil {
            fmt.Printf("解析消息中的段位失败: %v\n", err)
            return
        }

        rankToTrack, err := getAdjustedRankOrder(currentTracking.Rank, db)
        if err != nil {
            fmt.Printf("获取跟踪段位的排序失败: %v\n", err)
            return
        }
        // 根据指定方向比较段位级别
        if (currentTracking.Direction == "+" && rankInMessage >= rankToTrack) || 
            (currentTracking.Direction == "-" && rankInMessage <= rankToTrack) {
            sendTextMessage(msg.Content, sender.UserName)
            fmt.Printf("订单匹配发送给：%s\n", sender.NickName)
            err := UpdateTrackingStatus(db, currentTracking.StarredUser, sender.UserName, false)
            if err != nil {
                fmt.Printf("更新跟踪状态失败: %v\n", err)
            }                
        }
        return
    }    
}
func handlePrivateMessage(msgData Data) {
	var msg struct {
        Content      string
        FromUserName string
    }

    var sender struct {
        NickName string
        UserName string
    }

    // 将 Msg 中的字段赋值给 msg 和 sender 结构体
    msg.Content = msgData.StrContent           
    msg.FromUserName = msgData.UserName      

    sender.NickName = msgData.NickName  
    sender.UserName = msgData.UserName  
    currentTracking, err := checkActiveTracking(db, sender.UserName)
    if err != nil {
        fmt.Printf("检查活跃的跟踪状态失败: %v\n", err)
        return
    }
    // 在绑定码处理逻辑中，插入检查和合并逻辑
    bindCodePattern := regexp.MustCompile(`^\d{8}$`)
    if bindCodePattern.MatchString(msg.Content) {
        fmt.Printf("检测到可能是绑定码的消息: %s\n", msg.Content)

        // 尝试将消息作为绑定码处理
        openID, used, err := checkBindCode(msg.Content)
        if err != nil {
            fmt.Printf("检查绑定码失败: %v\n", err)
            // 不要发送消息，继续处理其他逻辑
        } else if used {
            fmt.Printf("绑定码 %s 已被使用\n", msg.Content)
            sendTextMessage("该绑定码已被使用，请在小程序中重新获取。", msg.FromUserName)
            return
        } else {
            fmt.Printf("找到有效的绑定码 %s, 关联的OpenID: %s\n", msg.Content, openID)

            // 开始事务
            tx, err := db.Begin()
            if err != nil {
                fmt.Printf("开始事务失败: %v\n", err)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            }

            // 检查是否已存在相同的 openid 或 wechatname
            var existingOpenID, existingWechatName string
            var existingBalance float64
            err = tx.QueryRow("SELECT openid, wechatname, balance FROM users WHERE openid = ? OR wechatname = ?", openID, sender.UserName).Scan(&existingOpenID, &existingWechatName, &existingBalance)
            
            if err == nil {
                // 存在记录，需要合并
                fmt.Printf("发现现有记录: openid=%s, wechatname=%s\n", existingOpenID, existingWechatName)

                // 如果 openid 已存在，更新 wechatname
                if existingOpenID == openID {
                    fmt.Printf("OpenID %s 已存在，更新 wechatname 为 %s\n", openID, sender.UserName)
                    _, err = tx.Exec("UPDATE users SET wechatname = ? WHERE openid = ?", sender.UserName, openID)
                    if err != nil {
                        tx.Rollback()
                        fmt.Printf("更新 wechatname 失败: %v\n", err)
                        sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                        return
                    }
                } else if existingWechatName == sender.UserName {
                    // 如果 wechatname 已存在但 openid 不同，合并记录
                    fmt.Printf("WeChatName %s 已存在，合并到 openid %s\n", sender.UserName, openID)

                    // 将现有记录的余额转移到新 openid
                    _, err = tx.Exec("UPDATE users SET balance = balance + ? WHERE openid = ?", existingBalance, openID)
                    if err != nil {
                        tx.Rollback()
                        fmt.Printf("合并余额失败: %v\n", err)
                        sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                        return
                    }

                    // 删除旧记录
                    _, err = tx.Exec("DELETE FROM users WHERE wechatname = ? AND openid != ?", sender.UserName, openID)
                    if err != nil {
                        tx.Rollback()
                        fmt.Printf("删除旧记录失败: %v\n", err)
                        sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                        return
                    }
                }
            } else if err != sql.ErrNoRows {
                // 发生了除"记录不存在"以外的错误
                tx.Rollback()
                fmt.Printf("查询现有记录失败: %v\n", err)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            } else {
                // 没有现有记录，插入新记录
                fmt.Printf("没有找到现有记录，插入新用户: openid=%s, wechatname=%s\n", openID, sender.UserName)
                _, err = tx.Exec("INSERT INTO users (openid, wechatname, balance) VALUES (?, ?, 0)", openID, sender.UserName)
                if err != nil {
                    tx.Rollback()
                    fmt.Printf("插入新用户失败: %v\n", err)
                    sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                    return
                }
            }

            // 在事务中标记绑定码为已使用
            res, err := tx.Exec(
                "UPDATE BindCodes SET used = 1 WHERE code = ? AND used = 0",
                msg.Content,
            )
            if err != nil {
                tx.Rollback()
                fmt.Printf("标记绑定码使用失败: %v\n", err)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            }

            affected, err := res.RowsAffected()
            if err != nil || affected == 0 {
                tx.Rollback()
                fmt.Printf("绑定码未能成功标记: %v, affected=%d\n", err, affected)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            }

            // 检查临时表中是否有该用户的余额记录
            var transferredBalance float64 = 0
            var transferMessage string
            var tempBalance float64
            err = tx.QueryRow("SELECT Balance FROM TempUserBalances WHERE WeChatUsername = ?", sender.UserName).Scan(&tempBalance)

            if err == nil {
                // 临时表中存在记录，将余额转入用户账户
                fmt.Printf("在临时表中找到用户 %s 的余额: %.2f，开始转移...\n", sender.UserName, tempBalance)

                // 更新用户余额
                _, err = tx.Exec("UPDATE users SET balance = balance + ? WHERE openid = ?", tempBalance, openID)
                if err != nil {
                    tx.Rollback()
                    fmt.Printf("更新用户余额失败: %v\n", err)
                    sendTextMessage("绑定成功，但转移余额失败，请联系客服。", msg.FromUserName)
                    return
                }

                // 记录余额转移交易
                transactionUUID := uuid.New().String()
                _, err = tx.Exec(
                    `INSERT INTO UserTransactions 
                    (ID, OpenID, TransactionType, Amount, ServiceFee, ActualAmount, Status, TransactionID, CreateTime) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    transactionUUID,
                    openID,
                    "临时余额转入",
                    tempBalance,
                    0,
                    tempBalance,
                    "成功",
                    "temp_balance_" + transactionUUID,
                    time.Now().Format("2006-01-02 15:04:05"),
                )
                if err != nil {
                    tx.Rollback()
                    fmt.Printf("记录余额转移交易失败: %v\n", err)
                    sendTextMessage("绑定成功，但转移余额失败，请联系客服。", msg.FromUserName)
                    return
                }

                // 从临时表中删除记录
                _, err = tx.Exec("DELETE FROM TempUserBalances WHERE WeChatUsername = ?", sender.UserName)
                if err != nil {
                    tx.Rollback()
                    fmt.Printf("从临时表中删除记录失败: %v\n", err)
                    sendTextMessage("绑定成功，但转移余额失败，请联系客服。", msg.FromUserName)
                    return
                }

                transferredBalance = tempBalance
                transferMessage = fmt.Sprintf("，并成功将 %.2f 元添加到您的账户", tempBalance)
                fmt.Printf("已成功将 %.2f 余额从临时表转入用户 %s 的账户\n", tempBalance, sender.UserName)
            } else if err != sql.ErrNoRows {
                // 发生了除"记录不存在"以外的错误
                tx.Rollback()
                fmt.Printf("查询临时表失败: %v\n", err)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            } else {
                // 临时表中没有记录，正常继续
                fmt.Printf("临时表中没有找到用户 %s 的记录\n", sender.UserName)
            }

            // 提交事务
            if err = tx.Commit(); err != nil {
                fmt.Printf("提交事务失败: %v\n", err)
                sendTextMessage("绑定失败，请稍后重试。", msg.FromUserName)
                return
            }

            // 如果转移了余额，尝试发送WebSocket通知更新用户余额
            if transferredBalance > 0 {
                notifyBalanceUpdate(openID)
            }

            fmt.Printf("成功将绑定码 %s 标记为已使用，用户: %s, OpenID: %s\n",
                msg.Content, sender.NickName, openID)

            // 构建成功消息
            successMessage := "绑定成功！现在您可以在小程序中使用接单系统"
            if transferredBalance > 0 {
                successMessage += transferMessage
            }

            sendTextMessage(successMessage, msg.FromUserName)
            fmt.Printf("已发送绑定成功消息给用户 %s\n", sender.NickName)
            return
        }
    } else {
        fmt.Printf("消息不是8位数字绑定码，继续其他处理\n")
    }
    // 检查是否有激活的跟踪实例和等待中的消息
    if currentTracking != nil && currentTracking.Active && currentTracking.WaitingFor.Valid && currentTracking.WaitingFor.String == sender.UserName {
        // 将消息转发给星标用户
        staruserName, err := findUserNameByNickName(currentTracking.StarredUser)
        if err != nil {
            fmt.Printf("查找失败")
        }
        sendTextMessage(msg.Content, staruserName)
        fmt.Printf("已将 %s 的消息转发给星标用户 %s。\n", sender.NickName, currentTracking.StarredUser)
        return
    }
    // 在handlePrivateMessage函数中添加处理逻辑
    if strings.Contains(msg.Content, "结账") {
        bridge, err := findBridgeByWeChatUser(sender.NickName)
        if err != nil {
            sendTextMessage(fmt.Sprintf("查询订单失败，请稍后重试：%v", err), msg.FromUserName)
            return
        }
        if bridge == nil {
            sendTextMessage("当前没有找到活跃的订单，请确认是否已经开始一个订单。", msg.FromUserName)
            return
        }
    
        switch bridge.OrderType {
        case "代练":
            message1 := fmt.Sprintf("哥，发一下进度，记录一下，复制下面的话，填上当前进度，格式如：#%s:进度：星耀22星", bridge.ID)
            message2 := fmt.Sprintf("#%s:进度：（进度）", bridge.ID)
            sendTextMessage(message1, msg.FromUserName)
            sendTextMessage(message2, msg.FromUserName)
    
        default:
            message1 := "哥，你打完了的话复制替换下面的话（去不去掉括号都行）记录一下，谢谢配合"
            message2 := "[老板发的名字][净胜]+[金额]"
            sendTextMessage(message1, msg.FromUserName)
            sendTextMessage(message2, msg.FromUserName)
        }
        return
    }
    if msgData.TypeInfo == "图片" {
        bridgeID, exists := pendingImages[sender.NickName]
        if exists {
            fmt.Println("需要将图片发送到指定群聊")
        
            bridge, err := findBridgeByID(bridgeID)
            if err != nil {
                fmt.Printf("Error finding bridge by ID: %v\n", err)
                return
            }
        
            if bridge.GroupID == "网站" {
                delete(pendingImages, sender.NickName)
                return
            } else {
                url := fmt.Sprintf("http://8.138.151.175:12590/?api=2209&userName=%s&msgSvrID=%s", bridge.GroupID, msgData.MsgSvrID)

                // 执行 GET 请求
                resp, err := http.Get(url)
                if err != nil {
                    fmt.Printf("发送 GET 请求失败: %v\n", err)
                    return
                }
                defer resp.Body.Close()

                // 检查响应状态
                if resp.StatusCode != http.StatusOK {
                    fmt.Printf("GET 请求返回错误状态: %d\n", resp.StatusCode)
                    return
                }

                // 输出请求成功的信息
                fmt.Println("GET 请求成功，图片转发完成")
          
              // 从映射中移除该用户
              delete(pendingImages, sender.NickName)
            }
        }else {
            var exist int
            err = db.QueryRow("SELECT COUNT(1) FROM UnsettledBridges WHERE WeChatUser = ? AND IsSettled = 0", sender.NickName).Scan(&exist)
            if err != nil {
                fmt.Printf("查询未结账记录失败: %v\n", err)
                return
            }

            if exist > 0 {
                fmt.Println("存在未结账记录，开始处理图片消息")
                fmt.Printf("正在转发消息，MsgSvrID: %s, userName: %s\n", msgData.MsgSvrID, "Moki-Flanke")
                // 构造转发消息的 URL，使用 GET 请求传递 userName 和 msgSvrID
                url := fmt.Sprintf("http://8.138.151.175:12590/?api=2209&userName=%s&msgSvrID=%s", "Moki-Flanke", msgData.MsgSvrID)

                // 执行 GET 请求
                resp, err := http.Get(url)
                if err != nil {
                    fmt.Printf("发送 GET 请求失败: %v\n", err)
                    return
                }
                defer resp.Body.Close()

                // 检查响应状态
                if resp.StatusCode != http.StatusOK {
                    fmt.Printf("GET 请求返回错误状态: %d\n", resp.StatusCode)
                    return
                }

                // 输出请求成功的信息
                fmt.Println("GET 请求成功，图片转发完成")

                // 处理未结账记录
                handleUnsettledRecords(sender.NickName, db)
            } else {
                fmt.Println("没有未结账记录，忽略图片消息")
            } 
        }
    }
  switch {
    case strings.Contains(msg.Content, "您已成功接手订单"):
        if currentTracking != nil && currentTracking.WaitingFor.Valid && currentTracking.WaitingFor.String == msg.FromUserName {
            // 更新数据库状态为活跃
            if err := updateTrackingActivity(db, currentTracking.StarredUser, true, false); err != nil {
                fmt.Printf("更新跟踪状态失败: %v\n", err)
                return
            }
            fmt.Printf("订单已被 %s 接手，正在跟踪其消息。\n", sender.NickName)
        }
        return
    case strings.Contains(msg.Content, "useropenid：") || strings.Contains(msg.Content, "useropenid:"):
        // 使用正则表达式提取 useropenid 后的 xxx
        re := regexp.MustCompile(`useropenid[：:]\s*(\S+)`)
        matches := re.FindStringSubmatch(msg.Content)
        if len(matches) > 1 {
            useropenid := matches[1]
            senderOpenid := msg.FromUserName
            senderWechatname := sender.NickName

            // 检查用户是否已存在
            var exists bool
            err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE openid = ?)", senderOpenid).Scan(&exists)
            if err != nil {
                fmt.Printf("查询用户失败: %v\n", err)
                return
            }

            if exists {
                // 更新现有用户的 useropenid 和 wechatname
                _, err = db.Exec("UPDATE users SET useropenid = ?, wechatname = ? WHERE openid = ?", useropenid, senderWechatname, senderOpenid)
                if err != nil {
                    fmt.Printf("更新用户失败: %v\n", err)
                    return
                }
                fmt.Printf("已更新用户 %s 的useropenid和wechatname\n", senderOpenid)
            } else {
                // 创建新用户
                username := senderWechatname // 注意：实际系统中需确保 username 唯一
                password := "123456" // 注意：实际系统中需妥善处理密码
                _, err = db.Exec("INSERT INTO users (username, password, openid, wechatname, useropenid) VALUES (?, ?, ?, ?, ?)",
                    username, password, senderOpenid, senderWechatname, useropenid)
                if err != nil {
                    fmt.Printf("创建新用户失败: %v\n", err)
                    return
                }
                fmt.Printf("已创建新用户 %s\n", senderOpenid)
            }
        } else {
            fmt.Println("消息中未找到useropenid后的内容")
        }
        return
    case msg.Content == "该订单已经被其他人接手" || msg.Content == "该订单已经被接手":
        if currentTracking != nil && currentTracking.WaitingFor.Valid && currentTracking.WaitingFor.String == msg.FromUserName {
            // 重新激活群监听
            if err := updateTrackingActivity(db, currentTracking.StarredUser, false, true); err != nil {
                fmt.Printf("更新跟踪状态失败: %v\n", err)
                return
            }
            fmt.Println("订单接手失败，重新激活群监听。")
        }
        return
    case strings.Contains(msg.Content, "再出") || strings.Contains(msg.Content, "下次") || strings.Contains(msg.Content, "在出"):
        // 增加完单数量
        err := incrementCompleteOrderCount(sender.NickName, db)
        if err != nil {
            fmt.Printf("更新完单数量失败：%v", err)
            return
        }
        err = clearWeChatUserFromActiveBridges(sender.NickName, db)
        if err != nil {
            fmt.Printf("清除活跃桥接中的用户失败：%v", err) 
            return
        }
        // 发送回复信息
        sendTextMessage("已通知老板重新点单，再次合作！哥", sender.UserName)

        return
    case strings.Contains(msg.Content, "复制信息发我，"):
        blacklisted, err := isUserBlacklisted(db, sender.NickName)
        if err != nil {
            fmt.Printf("Error checking blacklist: %v\n", err)
            return
        }
    
        if blacklisted {
            return
        }
    
        bridge, err := findBridgeForContent(msg.Content)
        if err != nil {
            fmt.Printf("Error finding bridge for content: %v\n", err)
            return
        }
    
        if bridge != nil {
            // 检查代发订单的拉黑逻辑
            if bridge.GroupName == "代发" {
                // 查询拉黑表，检查当前用户是否被拉黑
                var isBlacklisted bool
                err = db.QueryRow(`
                    SELECT EXISTS (
                        SELECT 1 FROM blacklist 
                        WHERE openid = ? 
                        AND username = (
                            SELECT userName FROM friends WHERE userName = ?
                        )
                        AND is_active = 1
                    )`, bridge.GroupID, msg.FromUserName).Scan(&isBlacklisted)
                
                if err != nil {
                    fmt.Printf("Error checking blacklist for proxy order: %v\n", err)
                    return
                }
                
                if isBlacklisted {
                    fmt.Printf("User %s is blacklisted for proxy order\n", msg.FromUserName)
                    return
                }
            }
    
            if bridge.WeChatUser == "" {
                updateBridgeWithWeChatUser(bridge, msg.FromUserName, sender.NickName)
                mapMutex.Lock()
                lastActiveUserMap[sender.NickName] = msg.FromUserName // 更新映射表，记录最新的活跃用户
                mapMutex.Unlock()
    
                username := bridge.GroupUserNickName
                orderID := bridge.ID
    
                if bridge.GroupName == "网站" {
                    // 网站情况：发送模板消息
                    sendMessageToUser(username, orderID, "text", "已有车队，请输入您的游戏名字，现在上号，同意好友")
                    
                    // 查询用户的 openid
                    var openid string
                    err = db.QueryRow("SELECT openid FROM users WHERE username = ?", username).Scan(&openid)
                    if err != nil {
                        fmt.Println("Error fetching openid:", err)
                        return
                    }
    
                    // 模板消息内容
                    data := map[string]TemplateData{
                        "time4":   TemplateData{Value: time.Now().Format("2006-01-02 15:04:05"), Color: "#173177"},
                        "thing10": TemplateData{Value: bridge.OrderType, Color: "#FF0000"},
                        "thing11": TemplateData{Value: "现在上号，没填名字需要进官网发送名字", Color: "#008000"},
                    }
    
                    // 构建模板消息
                    templateMessage := TemplateMessage{
                        Touser:     openid,
                        TemplateID: "8U6amkQYYrJ46famkxnkCM1hrv24ww9Yc1FuqVduVmA", // 替换为您的模板消息 ID
                        URL:        "https://www.moki-flanke.icu",
                        Data:       data,
                    }
    
                    accessToken, err := getAccessToken()
                    if err != nil {
                        fmt.Println("Error getting access token:", err)
                        return
                    }
    
                    err = sendTemplateMessage(accessToken, templateMessage)
                    if err != nil {
                        fmt.Println("Error sending template message:", err)
                        return
                    }
    
                    fmt.Println("Template message sent successfully!")
                
                } else if bridge.GroupName == "代发" {
                    // 订阅消息内容
                    data := map[string]interface{}{
                        "thing2": map[string]string{"value": bridge.Msg},
                        "thing3": map[string]string{"value": "已有人接单"},
                        "thing19": map[string]string{"value": sender.NickName},
                    }
    
                    // 构建订阅消息
                    subscribeMessage := map[string]interface{}{
                        "touser":           bridge.GroupID,
                        "template_id":      "9IyZj7NtfWP40VrC7VJwIoKXAgv194-agtHu6sSJN1s", // 替换为您的订阅消息 ID
                        "page":             "pages/order_list/order_list",
                        "miniprogram_state": "formal",
                        "lang":             "zh_CN",
                        "data":             data,
                    }
    
                    accessToken, err := getMiniAccessToken()
                    if err != nil {
                        fmt.Println("Error getting accessToken:", err)
                        return
                    }
    
                    err = sendSubscribeMessage(accessToken, subscribeMessage)
                    if err != nil {
                        fmt.Println("Error sending subscribe message:", err)
                        return
                    }
    
                    fmt.Println("Subscribe message sent successfully!")
                }
            } else if bridge.WeChatUser == sender.NickName {
                sendTextMessage("稍等老板发id，哥！", msg.FromUserName)
            } else {
                sendTextMessage("该订单已经被其他人接手", msg.FromUserName)
            }
        } else {
            sendTextMessage("该订单已经被接手", msg.FromUserName)
        }
        return
    case strings.HasPrefix(msg.Content, "#") || strings.HasPrefix(msg.Content, "＃"):
        // 处理群内成员与微信用户之间的对话
        handleBridgeConversation(db, msg.FromUserName, sender.NickName, msg.Content)
        input := strings.TrimPrefix(msg.Content, "#")
        ranksAndPrices, err := getRanksAndPrices(db)
        if err != nil {
            fmt.Printf("Error getting ranks and prices: %v\n", err)
            return
        }
    
        // 对ranksAndPrices按照段位长度进行排序
        var ranks []string
        for rank := range ranksAndPrices {
            ranks = append(ranks, rank)
        }
        sort.Slice(ranks, func(i, j int) bool {
            return len(ranks[i]) > len(ranks[j])
        })
        var matchedRanks []string
        totalPrice := 0
        for _, rank := range ranks {
            rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
            for i := 0; i < rankOccurrences; i++ {
                matchedRanks = append(matchedRanks, rank)
                totalPrice += ranksAndPrices[rank]
                input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
            }
        }
        // 检查是否有匹配的段位
        if len(matchedRanks) == 0 {
            fmt.Printf("不存在匹配段位")
            return // 结束函数执行
        }
        fmt.Printf("匹配的段位%s", matchedRanks)
        bridge, err := findBridgeByWeChatUser(sender.NickName)
        if err != nil {
            fmt.Printf("Error finding bridge: %v\n", err)
            return
        }
        if bridge == nil {
            fmt.Println("No active bridge found for user")
            return
        }
        fmt.Printf("Found bridge: %+v\n", bridge)
        if bridge.GroupName == "网站" {
            // 提取原始消息中的段位顺序
            originalRanks := extractOriginalRanks(bridge.Msg, ranks)

            // 按顺序替换为用户输入的段位
            newMsg := bridge.Msg
            for i := 0; i < len(originalRanks) && i < len(matchedRanks); i++ {
                originalRank := originalRanks[i]
                newRank := matchedRanks[i]
                // 替换第一个出现的originalRank为newRank
                newMsg = strings.Replace(newMsg, originalRank, newRank, 1)
            }
            bridge.Msg = newMsg

            // 更新数据库中的消息
            updateQuery := `
                UPDATE Bridges
                SET Msg = ?
                WHERE ID = ?
            `
            _, err := db.Exec(updateQuery, bridge.Msg, bridge.ID)
            if err != nil {
                fmt.Printf("Error updating bridge message: %v\n", err)
                return
            }
            sendTextMessage(fmt.Sprintf("已成功更新段位：%s", bridge.Msg), sender.UserName)
        }
        return 
    case strings.Contains(msg.Content, "没打"):
            // 查询最新的活跃桥接记录的 ID
        var bridgeID, bGroupID, bGroupUserNickName, bGroupName string
        err := db.QueryRow(`
            SELECT ID, GroupID, GroupUserNickName, GroupName
            FROM Bridges
            WHERE WeChatUser = ?
            ORDER BY CreatedAt DESC
            LIMIT 1
        `, sender.NickName).Scan(&bridgeID, &bGroupID, &bGroupUserNickName, &bGroupName)
        
        if err != nil {
            if err == sql.ErrNoRows {
                sendTextMessage("当前没有找到活跃的订单，请确认是否已经开始一个订单。", msg.FromUserName)
            } else {
                sendTextMessage(fmt.Sprintf("查询订单失败，请稍后重试：%v", err), msg.FromUserName)
            }
            return
        }

        // 获取最新的消息内容
        var message string
        var frozenStars int
        err = db.QueryRow("SELECT Message FROM BridgeMessages WHERE BridgeID = ? LIMIT 1", bridgeID).Scan(&message)
        
        if err != nil {
            sendTextMessage("成功记录老板没有打，再合作", msg.FromUserName)
            _, delErr := db.Exec("DELETE FROM Bridges WHERE ID = ?", bridgeID)
            if delErr != nil {
                log.Printf("删除Bridges记录失败: %v", delErr)
                sendTextMessage("没有找到订单", msg.FromUserName)
            }
        }
        if bGroupID == "网站" {
            // 查询冻结的星卷
            err := db.QueryRow("SELECT StarCost FROM StarFreeze WHERE ID = ?", bridgeID).Scan(&frozenStars)
            if err != nil {
                if err == sql.ErrNoRows {
                    frozenStars = 0 // 如果没有找到记录，则设为0
                    fmt.Printf("No frozen stars found for bridge ID [%s], setting frozenStars to 0\n", bridgeID)
                } else {
                    fmt.Printf("Error querying frozen stars for bridge ID [%s]: %v\n", bridgeID, err)
                    return // 处理错误，必要时返回或采取其他措施
                }
            } else {
                fmt.Printf("Found frozen stars [%d] for bridge ID [%s]\n", frozenStars, bridgeID)
            }
        } else {
            frozenStars = 0
            fmt.Printf("Bridge GroupID is not '网站', setting frozenStars to 0\n")
        }
        // 更新用户的星卷数
        if bGroupID == "网站" {
            // 获取用户名和AI群
            var aiGroup, name string
            err := db.QueryRow("SELECT ai_group, name FROM users WHERE username = ?", bGroupUserNickName).Scan(&aiGroup, &name)
            if err != nil {
                fmt.Printf("Error querying AI group: %v\n", err) // 打印错误信息
                return
            }

            if aiGroup == "" {
                // 如果没有AI群，更新用户表中的星卷数量
                _, err = db.Exec("UPDATE users SET star_journal = star_journal + ? WHERE username = ?", frozenStars, bGroupUserNickName)
                if err != nil {
                    fmt.Printf("Error updating stars for user: %v\n", err) // 打印错误信息
                } else {
                    fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bGroupUserNickName, frozenStars)
                }
            } else {
                // 更新群组中的星卷数量
                var existingStars int
                err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?", aiGroup, name).Scan(&existingStars)
                if err != nil && err != sql.ErrNoRows {
                    fmt.Printf("Error querying existing stars: %v\n", err) // 打印错误信息
                    return
                }

                if err == sql.ErrNoRows {
                    // 插入新记录
                    _, err = db.Exec("INSERT INTO member_stars (GroupID, UserName, StarsCount) VALUES (?, ?, ?)", aiGroup, name, -frozenStars)
                    if err != nil {
                        fmt.Printf("Error inserting new stars record: %v\n", err) // 打印错误信息
                    } else {
                        fmt.Printf("Successfully inserted new stars record for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, frozenStars)
                    }
                } else {
                    // 更新现有记录
                    _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount + ? WHERE GroupID = ? AND UserName = ?", frozenStars, aiGroup, name)
                    if err != nil {
                        fmt.Printf("Error updating stars for group: %v\n", err) // 打印错误信息
                    } else {
                        fmt.Printf("Successfully updated stars for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, frozenStars)
                    }
                }
            }

            // 删除冻结表中的记录
            _, err = db.Exec("DELETE FROM StarFreeze WHERE ID = ?", bridgeID)
            if err != nil {
                fmt.Printf("Error deleting frozen stars for bridge ID [%s]: %v\n", bridgeID, err)
            } else {
                fmt.Printf("Successfully deleted frozen stars for bridge ID [%s]\n", bridgeID)
            }
        } else {
            // 更新其他用户的星卷数
            _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount + ? WHERE UserName = ? AND GroupID = ?", frozenStars, bGroupUserNickName, bGroupName)
            if err != nil {
                fmt.Printf("Error updating stars for user [%s]: %v\n", bGroupUserNickName, err)
            } else {
                fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bGroupUserNickName, frozenStars)
            }
        }
        // 直接使用从消息中提取的值作为 gameID
        gameID := message // 假设 message 本身就是 gameID 的值

        // 修改 msg.Content 为 gameID + "0"
        msg.Content = fmt.Sprintf("%s0+0", gameID)

        // 调用 processNumericResponse
        processNumericResponse(msg.Content, msg.FromUserName, sender.NickName)
        return
    case strings.Contains(msg.Content, "扫码") || strings.Contains(msg.Content, "发码"):
        bridge, err := findBridgeByWeChatUser(sender.NickName)
        if err != nil {
            fmt.Sprintf("查询订单失败，请稍后重试：%v", err)
            return
        }
        if bridge == nil {
            fmt.Sprintf("当前没有找到活跃的订单，请确认是否已经开始一个订单。")
            return
        }
        pendingImages[sender.NickName] = bridge.ID
        sendTextMessage("已开启扫码功能，你发的下一张图片将直接发送给老板", sender.UserName)
    case isNumericContent(msg.Content) && msgData.TypeInfo != "图片":
        // 处理包含数字的消息
        checkFormattingAndRespond(msg.Content, msg.FromUserName, sender.NickName)
        return
    default:
        fmt.Printf("私聊消息不符合格式: %s\n", msg.Content)
    }
}
func extractOriginalRanks(msg string, ranks []string) []string {
    var originalRanks []string
    index := 0
    for index < len(msg) {
        maxLen := 0
        currentRank := ""
        // 查找当前位置开始的最长匹配段位
        for _, rank := range ranks {
            rankLen := len(rank)
            if index+rankLen <= len(msg) && msg[index:index+rankLen] == rank {
                if rankLen > maxLen {
                    maxLen = rankLen
                    currentRank = rank
                }
            }
        }
        if currentRank != "" {
            originalRanks = append(originalRanks, currentRank)
            index += maxLen // 移动到段位之后
        } else {
            index++ // 未找到段位，移动一个字符
        }
    }
    return originalRanks
}
// 获取或初始化群状态的函数
func GetGroupState(groupID string) *GroupState {
    state, exists := groupStates[groupID]
    if !exists {
        state = &GroupState{} // 如果状态不存在，则初始化
        groupStates[groupID] = state
    }
    return state
}
func forwardMessageToAllGroups(db *sql.DB, content string) {
    // 查询老板群的群昵称
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 2 AND event_title = '老板群'").Scan(&eventText)
    if err != nil {
        fmt.Println("从数据库获取老板群昵称列表失败:", err)
        return
    }

    // 解析 event_text 字符串为群昵称列表
    groupNicknames := strings.Split(eventText, "||")

    var groupUserNames []string

    for _, nickname := range groupNicknames {
        // +++ 新增过滤逻辑：跳过空群昵称 +++
        if strings.TrimSpace(nickname) == "" { // 同时过滤纯空格的情况
            fmt.Printf("警告：发现空群昵称，已跳过\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到群昵称 [%s] 对应的 userName\n", nickname)
                continue
            }
            fmt.Printf("查询群昵称 [%s] 对应的 userName 失败: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    // 遍历目标群组，逐个发送消息
    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}
func forwardMessageToAllGroupsneibu(db *sql.DB, content string) {
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 4 AND event_title = '内部接单'").Scan(&eventText)
    if err != nil {
        fmt.Println("从数据库获取内部接单群列表失败:", err) // 修改错误提示更准确
        return
    }

    groupNicknames := strings.Split(eventText, "||")
    var groupUserNames []string

    for _, nickname := range groupNicknames {
        // +++ 空群昵称过滤 +++
        if trimmed := strings.TrimSpace(nickname); trimmed == "" {
            fmt.Printf("警告：跳过空内部接单群昵称\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到内部接单群 [%s] 的userName\n", nickname)
                continue
            }
            fmt.Printf("查询内部接单群失败 [%s]: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}

func forwardMessageToAllGroupspeiwan(db *sql.DB, content string) {
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 5 AND event_title = '陪玩群'").Scan(&eventText)
    if err != nil {
        fmt.Println("获取陪玩群列表失败:", err)
        return
    }

    groupNicknames := strings.Split(eventText, "||")
    var groupUserNames []string

    for _, nickname := range groupNicknames {
        if trimmed := strings.TrimSpace(nickname); trimmed == "" {
            fmt.Printf("警告：跳过空陪玩群昵称\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到陪玩群 [%s] 的userName\n", nickname)
                continue
            }
            fmt.Printf("查询陪玩群失败 [%s]: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}

func forwardMessageToAllGroupsxjj(db *sql.DB, content string) {
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 6 AND event_title = '小姐姐'").Scan(&eventText)
    if err != nil {
        fmt.Println("获取小姐姐群列表失败:", err)
        return
    }

    groupNicknames := strings.Split(eventText, "||")
    var groupUserNames []string

    for _, nickname := range groupNicknames {
        if trimmed := strings.TrimSpace(nickname); trimmed == "" {
            fmt.Printf("警告：跳过空小姐姐群昵称\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到小姐姐群 [%s] 的userName\n", nickname)
                continue
            }
            fmt.Printf("查询小姐姐群失败 [%s]: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}

func forwardMessageToAllGroupsdailian(db *sql.DB, content string) {
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 7 AND event_title = '代练群'").Scan(&eventText)
    if err != nil {
        fmt.Println("获取代练群列表失败:", err)
        return
    }

    groupNicknames := strings.Split(eventText, "||")
    var groupUserNames []string

    for _, nickname := range groupNicknames {
        if trimmed := strings.TrimSpace(nickname); trimmed == "" {
            fmt.Printf("警告：跳过空代练群昵称\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到代练群 [%s] 的userName\n", nickname)
                continue
            }
            fmt.Printf("查询代练群失败 [%s]: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}

func forwardMessageToAllGroupswaibu(db *sql.DB, content string) {
    var eventText string
    err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 3 AND event_title = '外部发单群'").Scan(&eventText)
    if err != nil {
        fmt.Println("获取外部发单群列表失败:", err)
        return
    }

    groupNicknames := strings.Split(eventText, "||")
    var groupUserNames []string

    for _, nickname := range groupNicknames {
        if trimmed := strings.TrimSpace(nickname); trimmed == "" {
            fmt.Printf("警告：跳过空外部群昵称\n")
            continue
        }

        var userName string
        err := db.QueryRow("SELECT userName FROM groups WHERE nickName = ?", nickname).Scan(&userName)
        if err != nil {
            if err == sql.ErrNoRows {
                fmt.Printf("未找到外部群 [%s] 的userName\n", nickname)
                continue
            }
            fmt.Printf("查询外部群失败 [%s]: %s\n", nickname, err)
            return
        }
        groupUserNames = append(groupUserNames, userName)
    }

    for _, groupUserName := range groupUserNames {
        sendTextMessage(content, groupUserName)
    }
}
// 调用接口获取通讯录数据
func fetchContacts() ([]Record, error) {
	url := "http://8.138.151.175:12590/?api=2102&page=0&pageSize=500"

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var friendData FriendData
	err = json.Unmarshal(body, &friendData)
	if err != nil {
		return nil, err
	}

	// 返回通讯录记录
	return friendData.Data.Record, nil
}

// 保存到数据库
func saveToDatabase(records []Record) error {
	for _, record := range records {
        if strings.HasSuffix(record.UserName, "@chatroom") {
            // 保存到群组表
            err := saveGroup(record)
            if err != nil {
                fmt.Printf("保存群组失败: %s\n", err)
            }
        } else {
            // 保存到好友表
            err := saveFriend(record)
            if err != nil {
                fmt.Printf("保存好友失败: %s\n", err)
            }
        }
	}
	return nil
}

// 保存到好友表
func saveFriend(record Record) error {
	query := `
		INSERT INTO friends (userName, nickName, remark, bigHeadImgUrl)
		VALUES (?, ?, ?, ?)
		ON CONFLICT(userName) DO UPDATE SET 
			nickName = excluded.nickName,
			remark = excluded.remark,
			bigHeadImgUrl = excluded.bigHeadImgUrl
	`
	_, err := db.Exec(query, record.UserName, record.NickName, record.Remark, record.BigHeadImgUrl)
	return err
}

// 保存到群组表
func saveGroup(record Record) error {
	query := `
		INSERT INTO groups (userName, nickName)
		VALUES (?, ?)
		ON CONFLICT(userName) DO UPDATE SET 
			nickName = excluded.nickName
	`
	_, err := db.Exec(query, record.UserName, record.NickName)
	return err
}

// 更新通讯录
func updateContacts() error {
	// 调用接口获取通讯录数据
	records, err := fetchContacts()
	if err != nil {
		return fmt.Errorf("failed to fetch contacts: %w", err)
	}

	// 保存到数据库
	err = saveToDatabase(records)
	if err != nil {
		return fmt.Errorf("failed to save contacts to database: %w", err)
	}

	fmt.Println("Contacts saved to database successfully.")
	return nil
}
// 发送添加好友请求
func sendAddFriendRequest(encryptUserName, ticket string, port int) error {
	// 构造 POST 请求数据
	requestBody := AddFriendRequest{
		API: 2314,
		Data: FriendPostData{
			EncryptUserName: encryptUserName,
			Ticket:          ticket,
			scene:           14,
			rights:          0,
		},
	}

	// 将数据转换为 JSON
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		return fmt.Errorf("序列化请求数据失败: %w", err)
	}

	// 构建请求 URL
	url := fmt.Sprintf("http://8.138.151.175:%d", port)

	// 发送 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("发送 POST 请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("POST 请求返回错误状态: %d", resp.StatusCode)
	}

	fmt.Println("POST 请求成功，好友添加接口调用完成")
	return nil
}

// 发送文本消息
func sendTextMessagePort(content, userName string, port int) {
	// 构造 POST 请求数据
	requestBody := map[string]interface{}{
		"api": 2200,
		"data": map[string]string{
			"content":  content,
			"userName": userName,
            "isNew": strconv.Itoa(1),
		},
	}

	// 将数据转换为 JSON
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Printf("序列化请求数据失败: %v\n", err)
		return
	}

	// 构建请求 URL
	url := fmt.Sprintf("http://8.138.151.175:%d", port)

	// 发送 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Printf("发送 POST 请求失败: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		log.Printf("POST 请求返回错误状态: %d\n", resp.StatusCode)
		return
	}

	// 打印成功信息
	fmt.Printf("POST 请求成功，向 [%s] 发送消息完成\n", userName)
}

// 发送图片消息
func sendImagePort(imageFileName, userName string, port int) error {
	// 构造 POST 请求数据
	requestBody := map[string]interface{}{
		"api": 2201,
		"data": map[string]string{
			"imgFileName": imageFileName,
			"userName":    userName,
            "isNew": strconv.Itoa(1),
		},
	}

	// 将数据转换为 JSON
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		return fmt.Errorf("序列化请求数据失败: %w", err)
	}

	// 构建请求 URL
	url := fmt.Sprintf("http://8.138.151.175:%d", port)

	// 发送 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("发送 POST 请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("POST 请求返回错误状态: %d", resp.StatusCode)
	}

	fmt.Printf("POST 请求成功，向 [%s] 发送消息完成\n", userName)
	return nil
}


func sendTextMessage(content, userName string) {
    // 请求间隔控制
    sendMu.Lock()
    defer sendMu.Unlock()
    
    // 计算需要等待的时间
    if elapsed := time.Since(lastSent); elapsed < 300*time.Millisecond {
        waitTime := 500*time.Millisecond - elapsed
        log.Printf("请求间隔 %.2fs，等待 %.2fs", elapsed.Seconds(), waitTime.Seconds())
        time.Sleep(waitTime)
    }
    
    // 记录本次请求时间
    lastSent = time.Now()
    
    // 在请求体中默认添加isNew="1"
    requestBody := map[string]interface{}{
        "api": 2200,
        "data": map[string]interface{}{
            "content":  content,
            "userName": userName,
            "isNew":    "1",
        },
    }
    
    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        log.Printf("序列化请求数据失败: %v", err)
        return
    }
    
    resp, err := http.Post("http://8.138.151.175:12590", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        log.Printf("发送 POST 请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    if resp.StatusCode != http.StatusOK {
        log.Printf("POST 请求返回错误状态: %d", resp.StatusCode)
        return
    }
    
    fmt.Printf("POST 请求成功，向 [%s] 发送消息完成\n", userName)
}
func sendImage(image_file_name, userName string) error {
    // 构造 POST 请求数据
    requestBody := map[string]interface{}{
        "api": 2201,
        "data": map[string]string{
            "imgFileName":  image_file_name,
            "userName": userName,
            "isNew": strconv.Itoa(1),
        },
    }

    // 将数据转换为 JSON
    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        return fmt.Errorf("序列化请求数据失败: %w", err)
    }

    // 发送 POST 请求
    resp, err := http.Post("http://8.138.151.175:12590", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        return fmt.Errorf("发送 POST 请求失败: %w", err)
    }
    defer resp.Body.Close()

    // 检查响应状态
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("POST 请求返回错误状态: %d", resp.StatusCode)
    }

    fmt.Printf("POST 请求成功，向 [%s] 发送消息完成\n", userName)
    return nil
}
func closeBridge(groupID, nickName string) error {
    // 查询符合条件的桥梁记录
    rows, err := db.Query("SELECT WeChatUser, GameID FROM Bridges WHERE GroupID = ? AND GroupUserNickName = ? AND IsActive = 1", groupID, nickName)
    if err != nil {
        fmt.Printf("Error querying bridges for member [%s] in group [%s]: %v\n", nickName, groupID, err)
        return err
    }
    defer rows.Close()

    for rows.Next() {
        var weChatUser, gameID string
        if err := rows.Scan(&weChatUser, &gameID); err != nil {
            fmt.Printf("Error scanning bridge row: %v\n", err)
            continue
        }

        // 如果GameID为空，则发送提醒消息
        if gameID == "" {
            weChatUserName, err := findUserNameByNickName(weChatUser)
            if err != nil {
                fmt.Printf("Error finding user name by nick name [%s]: %v\n", weChatUser, err)
                continue
            }
            content := "哥，老板重新点单了，你发一下“结账”根据提示记录结账"
			sendTextMessage(content, weChatUserName)
        }
    }

    // 处理错误
    if err := rows.Err(); err != nil {
        fmt.Printf("Error iterating over bridges: %v\n", err)
        return err
    }

    // 更新桥梁记录为非活跃状态
    _, err = db.Exec("UPDATE Bridges SET IsActive = 0 WHERE GroupID = ? AND GroupUserNickName = ? AND IsActive = 1", groupID, nickName)
    if err != nil {
        fmt.Printf("Error closing bridges for member [%s] in group [%s]: %v\n", nickName, groupID, err)
        return err
    }
    fmt.Printf("关闭桥梁: 群 [%s] 用户 [%s]\n", groupID, nickName)
    return nil
}
func findUserNameByNickName(nickName string) (string, error) {
    mapMutex.Lock() // 在读取映射之前加锁
    if userName, ok := lastActiveUserMap[nickName]; ok {
        mapMutex.Unlock() // 读取后解锁
        return userName, nil
    }
    mapMutex.Unlock() // 确保在任何出口处都释放锁
    
    // 如果缓存中没有，查询数据库，优先选择wxid开头的用户名
    var userName string
    err := db.QueryRow("SELECT userName FROM friends WHERE nickName = ? ORDER BY CASE WHEN userName LIKE 'wxid_%' THEN 0 ELSE 1 END LIMIT 1", nickName).Scan(&userName)
    if err != nil {
        if err == sql.ErrNoRows {
            return "", fmt.Errorf("no user found with nickname: %s", nickName)
        }
        return "", err
    }
    
    // 查询到结果后，更新缓存
    mapMutex.Lock() // 更新映射前加锁
    lastActiveUserMap[nickName] = userName // 更新映射
    mapMutex.Unlock() // 更新后解锁
    
    return userName, nil
}
// 修改原有的findBridge函数，使其使用数据库
func findBridge(groupID, nickName string) *Bridge {
    bridge, err := findBridgeFromDB(groupID, nickName)
    if err != nil {
        fmt.Printf("Error finding bridge from DB: %v\n", err)
        // 处理错误
        return nil
    }
    return bridge
}

func findBridgeFromDB(groupID, nickName string) (*Bridge, error) {
    bridge := &Bridge{}
    err := db.QueryRow(`
        SELECT * FROM Bridges WHERE GroupID = ? AND GroupUserNickName = ? AND IsActive = 1 ORDER BY CreatedAt DESC
        LIMIT 1
    `, groupID, nickName).Scan(
        &bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.GroupUserNickName,
        &bridge.WeChatUser, &bridge.IsActive, &bridge.IsCompleted, &bridge.Msg,
        &bridge.GameID, &bridge.Stars, &bridge.StarCost, &bridge.OrderType,
        &bridge.CreatedAt, &bridge.LastMessageTime, &bridge.FinalRank, &bridge.WeChatUsername, // 添加WeChatUsername
    )
    if err != nil {
        return nil, err
    }
    return bridge, nil
}
func queryMemberStars(db *sql.DB, groupName string, nickname string) int {
    if db == nil {
        fmt.Println("数据库连接未初始化")
        return 0  // 或者适当地处理这种情况
    }
    var totalStars int
    query := "SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?"
    err := db.QueryRow(query, groupName, nickname).Scan(&totalStars)
    fmt.Printf("Querying stars for user %s in group %s\n", nickname, groupName)
    if err != nil {
        if err == sql.ErrNoRows {
            // 未找到记录，用户可能还没有星卷记录
            fmt.Printf("No stars record for user %s in group %s\n", nickname, groupName)
            return 0
        } else {
            fmt.Printf("Error querying stars: %v\n", err)
            return 0 // 或者你可以选择返回一个错误
        }
    }
    fmt.Printf("Stars count for user %s in group %s: %d\n", nickname, groupName, totalStars)
    return totalStars
}

func getRanksAndPrices(db *sql.DB) (map[string]int, error) {
    ranksAndPrices := make(map[string]int)
    rows, err := db.Query("SELECT Rank, Price FROM RankPrices")
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    for rows.Next() {
        var rank string
        var price int
        err := rows.Scan(&rank, &price)
        if err != nil {
            continue // 或处理错误
        }
        ranksAndPrices[rank] = price
    }
    return ranksAndPrices, nil
}

func parsePeakRank(input string) (matchedRank string, nearestRank string) {
    peakRankRegex := regexp.MustCompile(`巅峰(\d+)`)
    matches := peakRankRegex.FindStringSubmatch(input)
    if len(matches) < 2 {
        return "", "" // 未匹配到有效的巅峰段位
    }

    inputRank, err := strconv.Atoi(matches[1])
    if err != nil {
        return matches[0], "" // 返回原始匹配，没有最近段位
    }

    // 定义巅峰段位的标准范围
    peakStages := []int{1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725, 1750, 1775, 1800, 1825, 1850, 1875, 1900,
        1925, 1950, 1975, 2000, 2025, 2050, 2075, 2100, 2125, 2150, 2175, 2200}
    smallestDiff := math.MaxInt32 // 使用最大整数作为初始的最小差值

    for _, rank := range peakStages {
        diff := abs(inputRank - rank)
        if diff < smallestDiff {
            smallestDiff = diff
            nearestRank = fmt.Sprintf("巅峰%d", rank)
        }
    }

    return matches[0], nearestRank
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func proceedWithCalculation(db *sql.DB, matchedRanks string, stars int, updatedInput string, originalPeak string, groupName string, senderNickName string, senderUserName string) {
    // 计算星卷消耗以及可能的最高段位
    maxUpgrades, _, remainingStars, err := calculateMaxRank(db, stars, []string{matchedRanks}, "车队")
    if err != nil {
        fmt.Printf("Error calculating max rank: %v\n", err)
        return
    }

    peakBase, _ := strconv.Atoi(originalPeak[6:]) // assuming "巅峰xxxx" format
    maxRankReached := fmt.Sprintf("%d", peakBase + maxUpgrades*25)

    if maxUpgrades == 0 {
        message := fmt.Sprintf("你的星卷不足，请扫码下方二维码联系群主获取更多星卷！当前星卷为%d", remainingStars)
        sendTextMessage(message, senderUserName)
        if err := sendImage(orderModeImage2, senderUserName); err != nil {
            fmt.Printf("发送图片失败: %v\n", err)
        }
        return
    }

    // 查询数据库中的价格
    var price int
    err = db.QueryRow("SELECT Price FROM RankPrices WHERE Rank = ?", matchedRanks).Scan(&price)
    if err != nil {
        fmt.Printf("Error fetching price: %v\n", err)
        return
    }

    // 构建输出内容
    content := fmt.Sprintf("%s%s，单价(25分)：%d, 最多到%s，复制信息发我，#通天代接", updatedInput, originalPeak, price, maxRankReached)
    forwardMessageToAllGroupsdailian(db, content)
    // 响应文本不再需要心形符号，现在反映最高可能达到的段位
    createBridge(senderUserName, groupName, senderNickName, content, "代练", 0)
    sendTextMessage(fmt.Sprintf("好勒！现在给你找通天代大佬了！乖乖别动哈！你目前能达到的最高段位为%s", maxRankReached), senderUserName)

}

func calculateMaxRank(db *sql.DB, currentStars int, initialRanks []string, mode string) (int, []string, int, error) {
    ranksCosts, err := getAllRanksAndCosts(db)
    if err != nil {
        return 0, nil, 0, err
    }

    startIndexes := make([]int, len(initialRanks))
    maxRanksReached := make([]string, len(initialRanks))
    for i, rankCost := range ranksCosts {
        for j, initialRank := range initialRanks {
            if rankCost[0] == initialRank {
                startIndexes[j] = i
                maxRanksReached[j] = initialRank  // Initialize with the initial rank
            }
        }
    }

    totalStars := currentStars
    upgrades := 0
    // Check mode to determine if cost should be halved
    if mode == "代练" { // Assuming "代练" is the mode indicating coaching
        totalStars *= 2
    }

    for totalStars > 0 {
        sharedUpgradePossible := true
        starCostSum := 0

        for _, index := range startIndexes {
            if index >= len(ranksCosts) {
                sharedUpgradePossible = false
                break
            }
            starCost, _ := strconv.Atoi(ranksCosts[index][1])
            starCostSum += starCost
        }

        if !sharedUpgradePossible || totalStars < starCostSum {
            break
        }
        totalStars -= starCostSum
        upgrades++
        for i := range startIndexes {
            startIndexes[i]++  // Move to next rank for all initial ranks
            if startIndexes[i] < len(ranksCosts) {
                maxRanksReached[i] = ranksCosts[startIndexes[i]][0]  // Update the highest rank reached for each initial rank
            }
        }
    }
    
    if mode == "代练" {
        totalStars /= 2  
    }

    return upgrades, maxRanksReached, totalStars, nil
}

func getAllRanksAndCosts(db *sql.DB) ([][2]string, error) {
    var ranksCosts [][2]string

    // 确保查询结果按照RankOrder排序
    query := "SELECT Rank, StarCost FROM RankPrices ORDER BY RankOrder ASC"
    rows, err := db.Query(query)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    for rows.Next() {
        var rank string
        var starCost int
        if err := rows.Scan(&rank, &starCost); err != nil {
            continue // 处理错误
        }
        ranksCosts = append(ranksCosts, [2]string{rank, strconv.Itoa(starCost)})
    }

    if err = rows.Err(); err != nil {
        return nil, err
    }

    return ranksCosts, nil
}

func createBridge(groupID, groupName, nickName, msgContent, orderType string, starCost int) {
    // 定义一个新的变量 finalOrderType 来存储处理后的订单类型
    validOrderTypes := map[string]bool{
        "车队":   true,
        "代练":   true,
        "陪玩":   true,
        "小姐姐": true,
    }

    finalOrderType := orderType
    if !validOrderTypes[orderType] {
        finalOrderType = "车队"
    }

    // 创建新桥梁
    newBridge := Bridge{
        ID:                uuid.New().String()[:32],
        GroupID:           groupID,
        GroupName:         groupName,
        GroupUserNickName: nickName,
        WeChatUser:        "",  // 初始时未指定微信用户
        IsActive:          true,
        IsCompleted:       false,
        Msg:               msgContent,
        GameID:            "",  // 初始时游戏ID为空
        StarCost:          0,
        Stars:             0,
        OrderType:         finalOrderType, // 使用处理后的订单类型
        CreatedAt:         time.Now(),
        LastMessageTime:   time.Now(), // 追踪最后消息时间
        FinalRank:         sql.NullString{String: "", Valid: false},
    }

    err := createBridgeInDB(newBridge)
    if err != nil {
        fmt.Printf("Error creating bridge in DB: %v\n", err)
        // 处理错误
    }

    // 如果 groupID 为 "网站"，在 WebOrders 表中插入数据
    if groupID == "网站" {
        insertWebOrderSQL := `INSERT INTO WebOrders (ID, Username, IsWebOrder) VALUES (?, ?, ?)`
        _, err := db.Exec(insertWebOrderSQL, newBridge.ID, nickName, 1)
        if err != nil {
            fmt.Printf("Error inserting into WebOrders table: %v\n", err)
        }
        // 插入星卷冻结表数据
        insertStarFreezeSQL := `INSERT INTO StarFreeze (Username, ID, StarCost) VALUES (?, ?, ?)`
        _, err = db.Exec(insertStarFreezeSQL, nickName, newBridge.ID, starCost)
        if err != nil {
            fmt.Printf("Error inserting into StarFreeze table: %v\n", err)
        }
    }
}

// 创建桥梁到数据库
func createBridgeInDB(bridge Bridge) error {
    // 假设您已经在您的数据库表中添加了 'FinalRank' 列
    stmt, err := db.Prepare(`
        INSERT INTO Bridges (
            ID, GroupID, GroupName, GroupUserNickName, WeChatUser, IsActive, 
            IsCompleted, Msg, GameID, Stars, StarCost, OrderType, CreatedAt, LastMessageTime, FinalRank
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `)
    if err != nil {
        return err
    }

    _, err = stmt.Exec(
        bridge.ID, bridge.GroupID, bridge.GroupName, bridge.GroupUserNickName,
        bridge.WeChatUser, bridge.IsActive, bridge.IsCompleted, bridge.Msg,
        bridge.GameID, bridge.Stars, bridge.StarCost, bridge.OrderType,
        bridge.CreatedAt, bridge.LastMessageTime, bridge.FinalRank,
    )
    return err
}

func handleBridgeConversation(db *sql.DB, senderUserName string, senderNickName string, contact string) {
	if strings.HasSuffix(senderUserName, "@chatroom") {
		handleGroupBridgeConversation(senderUserName, senderNickName, contact)
	} else if strings.HasPrefix(senderUserName, "wxid_") {
		handlePrivateBridgeConversation(db, senderUserName, senderNickName, contact)
	}
}

func handleGroupBridgeConversation(senderUserName string, senderNickName string, contact string) {
    contact = strings.Replace(contact, "＃", "#", -1)

    bridge := findBridge(senderUserName, senderNickName)
    if bridge != nil && bridge.IsActive && strings.HasPrefix(contact, "#") {
        content := strings.TrimPrefix(contact, "#")
        additionalMessage := bridge.ID + ":上面老板发的，私加老板免单举报，打完发#结账"
        
        weChatUserName, err := findUserNameByNickName(bridge.WeChatUser)
        if err != nil {
            fmt.Printf("未找到昵称对应的微信用户: %v\n", err)
            return
        }

		sendTextMessage(content, weChatUserName)
        sendTextMessage(additionalMessage, weChatUserName)
        updateBridgeMessageHistory(bridge.ID, content)
    }
}
func updateBridgeMessageHistory(bridgeID, message string) {
    // 添加Role字段插入，固定值为"老板"
    _, err := db.Exec("INSERT INTO BridgeMessages (BridgeID, Message, Role) VALUES (?, ?, '老板')", 
        bridgeID, 
        message)
    if err != nil {
        fmt.Printf("Error inserting new message for bridge [%s]: %v\n", bridgeID, err)
    }
}

func handlePrivateBridgeConversation(db *sql.DB, senderUserName string, senderNickName string, contact string) {
    // 规范化输入，确保全角井号被转换为半角井号
    contact = strings.Replace(contact, "＃", "#", -1)
    if strings.HasPrefix(contact, "#") {
        normalizedContent := strings.Replace(contact, "：", ":", -1)
        parts := strings.SplitN(normalizedContent, ":", 2)
        if len(parts) < 2 {
            fmt.Println("私聊命令格式不正确，需要 #BridgeID:对话内容")
            return
        }

        bridgeID := strings.TrimPrefix(parts[0], "#")
        bridge, err := findBridgeByID(bridgeID)
        if err != nil {
            fmt.Printf("Error finding bridge by ID: %v\n", err)
            return
        }
        if bridge == nil || !bridge.IsActive {
            fmt.Printf("未找到BridgeID [%s] 对应的桥梁\n", bridgeID)
            return
        }
        username := bridge.GroupUserNickName
        orderID := bridge.ID

        content := parts[1]

        switch bridge.OrderType {
        case "车队":
            if bridge.GroupID == "网站" {
                // 发送消息给前端用户
                sendMessageToUser(username, orderID, "text", content)
            }else{
                forwardContent := fmt.Sprintf("@%s %s", bridge.GroupUserNickName, content)
                sendTextMessage(forwardContent, bridge.GroupID)
            }
            
        case "陪玩":
            if bridge.GroupID == "网站" {
                // 发送消息给前端用户
                sendMessageToUser(username, orderID, "text", content)
                re := regexp.MustCompile(`编号\s*(.+)`)
                matches := re.FindStringSubmatch(content)
                if len(matches) > 1 {
                    identifier := matches[1]
                    imagePath := fmt.Sprintf("./image/%s.jpg", identifier)
                    sendImageToUser(username, orderID, imagePath)
                    return
                }
            }
            re := regexp.MustCompile(`编号\s*(.+)`)
            matches := re.FindStringSubmatch(content)
            if len(matches) > 1 {
                identifier := matches[1]
                imagePath := fmt.Sprintf("./image/%s.jpg", identifier)
                audioPath := fmt.Sprintf("./voice/%s.MP3", identifier)
                sendImageToUser(username, orderID, imagePath)
                sendMP3ToUser(username, orderID, audioPath)
            }
        case "小姐姐":
            if bridge.GroupID == "网站" {
                // 发送消息给前端用户
                sendMessageToUser(username, orderID, "text", content)
                re := regexp.MustCompile(`编号\s*(.+)`)
                matches := re.FindStringSubmatch(content)
                if len(matches) > 1 {
                    identifier := matches[1]
                    imagePath := fmt.Sprintf("./image/%s.jpg", identifier)
                    sendImageToUser(username, orderID, imagePath)
                    return
                }
            }
            re := regexp.MustCompile(`编号\s*(.+)`)
            matches := re.FindStringSubmatch(content)
            if len(matches) > 1 {
                identifier := matches[1]
                imagePath := fmt.Sprintf("./image/%s.jpg", identifier)
                audioPath := fmt.Sprintf("./voice/%s.MP3", identifier)
                sendImageToUser(username, orderID, imagePath)
                sendMP3ToUser(username, orderID, audioPath)
            }
        case "代练":
            if bridge.GroupID == "网站" {
                // 发送消息给前端用户
                sendMessageToUser(username, orderID, "text", content)
                if strings.HasPrefix(content, "铂金") || strings.HasPrefix(content, "钻石") || strings.HasPrefix(content, "星耀") || strings.HasPrefix(content, "王者") {
                    progressContent := strings.Trim(content, "（）")
                    fmt.Printf("收到段位相关的消息: %s\n", content)
                    
                    ranksCosts, err := getAllRanksAndCosts(db)
                    if err != nil {
                        fmt.Printf("获取所有段位和消耗信息失败：%v\n", err)
                        return
                    }
                    
                    matchedPeak, nearestPeak := parsePeakRank(bridge.Msg)
                    var peakBase int
                    if matchedPeak != "" {
                        peakBase, _ = strconv.Atoi(matchedPeak[6:])
                    }
                    var initialRanks []string
                    if nearestPeak != "" {
                        initialRanks = []string{nearestPeak}
                    } else {
                        sort.Slice(ranksCosts, func(i, j int) bool {
                            return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                        })
                        for _, rankCost := range ranksCosts {
                            if strings.Contains(bridge.Msg, rankCost[0]) {
                                initialRanks = append(initialRanks, rankCost[0])
                                break
                            }
                        }
                    }
                    fmt.Printf("初始段位: %v\n", initialRanks)
                    startIndex, err := getAdjustedRankOrder(initialRanks[0], db)
                    if err != nil {
                        fmt.Printf("获取橙色标记的段位排序失败: %v\n", err)
                        return
                    }
                    orangeIndex, err := extractRankFromMessage(bridge.Msg, db)
                    if err != nil {
                        fmt.Printf("解析消息中的初始段位失败: %v\n", err)
                        return
                    }
                    re := regexp.MustCompile(",最多打(\\d+)♥|,最多到(\\d+)")
                    matches := re.FindStringSubmatch(bridge.Msg)
                    var maxUpgrades int
                    var finalTargetRank int
                    if len(matches) > 1 {
                        for _, match := range matches[1:] {
                            if match != "" {
                                temp, _ := strconv.Atoi(match)
                                if strings.Contains(bridge.Msg, "最多到") {
                                    finalTargetRank = temp
                                    if peakBase > 0 {
                                        maxUpgrades = (finalTargetRank - peakBase) / 25
                                    }
                                } else {
                                    maxUpgrades = temp
                                }
                                break
                            }
                        }
                    }
                    orangeIndex += maxUpgrades
                    var zuizhong string
                    if !strings.Contains(progressContent, "巅峰") {
                        re := regexp.MustCompile(`^\d+$`)
                        if re.MatchString(progressContent) {
                            zuizhong = "巅峰" + progressContent
                        }
                    }
                
                    _, progressNearestPeak := parsePeakRank(zuizhong)
                    if progressNearestPeak != "" {
                        progressContent = progressNearestPeak
                    }
    
                    endIndex, err := getAdjustedRankOrder(progressContent, db)
                    if err != nil {
                        fmt.Printf("获取橙色标记的段位排序失败: %v\n", err)
                        return
                    }
                
                    if startIndex != -1 && endIndex != -1 {
                        upgradeCount := endIndex - startIndex
                        updateUserTotalStars(senderNickName, upgradeCount, bridge, 0)
                        _, err = db.Exec("UPDATE Bridges SET FinalRank = ? WHERE ID = ?", progressContent, bridge.ID)
                        if err != nil {
                            fmt.Printf("更新桥接[%s]的最终段位失败：%v\n", bridge.ID, err)
                        } else {
                            fmt.Printf("成功更新桥接[%s]的最终段位至[%s]\n", bridge.ID, progressContent)
                        }
                        if endIndex < orangeIndex {
                            var chaju int
                            chaju = orangeIndex - endIndex
                            sendTextMessage(fmt.Sprintf("已记录成功，距完单还差%d星，辛苦了，哥", chaju), senderUserName)

                        }
                        if endIndex >= orangeIndex {
                            sendTextMessage("已记录成功，您的订单已完成，发#完单，会自动结账", senderUserName)
                        }
                        _, totalStarsNeeded, err := getTargetRankAndPriceSum(db, initialRanks, upgradeCount)
                        if err != nil {
                            fmt.Printf("Error calculating target rank and stars: %v\n", err)
                            return
                        }
            
                        // 如果订单类型是"代练"，将星卷消耗除以2
                        if matchedPeak == "" {
                            totalStarsNeeded = (totalStarsNeeded + 1) / 2
                        }
                        // 检查是否存在支出记录
                        var existingPayment int
                        queryExpenditureSQL := `SELECT Payment FROM Expenditures WHERE NickName = ? AND BridgeID = ?`
                        err = db.QueryRow(queryExpenditureSQL, senderNickName, bridge.ID).Scan(&existingPayment)

                        if err != nil {
                            if err == sql.ErrNoRows {
                                // 没有支出记录，插入新的记录
                                insertExpenditureSQL := `INSERT INTO Expenditures (NickName, Payment, BridgeID) VALUES (?, ?, ?)`
                                _, err = db.Exec(insertExpenditureSQL, senderNickName, totalStarsNeeded, bridge.ID)
                                if err != nil {
                                    fmt.Printf("Error inserting expenditure record: %v\n", err)
                                    return
                                }
                                fmt.Printf("Inserted new expenditure record for NickName: %s, BridgeID: %s\n", senderNickName, bridge.ID)
                            } else {
                                // 查询过程中发生了其他错误
                                fmt.Printf("Error querying expenditure record: %v\n", err)
                                return
                            }
                        } else {
                            // 存在支出记录，更新记录
                            updateExpenditureSQL := `UPDATE Expenditures SET Payment = ? WHERE NickName = ? AND BridgeID = ?`
                            _, err = db.Exec(updateExpenditureSQL, totalStarsNeeded, senderNickName, bridge.ID)
                            if err != nil {
                                fmt.Printf("Error updating expenditure record: %v\n", err)
                                return
                            }
                            fmt.Printf("Updated expenditure record for NickName: %s, BridgeID: %s\n", senderNickName, bridge.ID)
                        }

                        fmt.Printf("支付:%d", totalStarsNeeded)   
                        // 发送 HTTP 请求
                        data := PaymentData{
                            BridgeID:    bridge.ID,
                            Payment:     totalStarsNeeded,
                            Debtor:      senderNickName,
                            Creditor:    "国服车队联系员-梦乐",
                        }
    
                        jsonData, err := json.Marshal(data)
                        if err != nil {
                            fmt.Printf("Error marshaling data: %v\n", err)
                            return
                        }
    
                        url := "http://www.moki-flanke.icu:8080/api/payment" // 替换为实际的 API 路由
                        req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
                        if err != nil {
                            fmt.Printf("Error creating request: %v\n", err)
                            return
                        }
    
                        req.Header.Set("Content-Type", "application/json")
    
                        client := &http.Client{}
                        resp, err := client.Do(req)
                        if err != nil {
                            fmt.Printf("Error sending request: %v\n", err)
                            return
                        }
                        defer resp.Body.Close()
    
                        if resp.StatusCode != http.StatusOK {
                            fmt.Printf("Error response from server: %v\n", resp.Status)
                        }
    
                        fmt.Println("请求已成功发送")  
                    } else {
                        fmt.Println("进度计算错误或段位顺序不正确")
                    }
                }       
                return
            }
            if content == "您好！现在准备扫码" {
                pendingImages[senderNickName] = bridge.ID
                forwardContent := fmt.Sprintf("@%s %s", bridge.GroupUserNickName, content)
                sendTextMessage(forwardContent, bridge.GroupID)
                sendTextMessage("已开启扫码功能，你发的下一张图片将直接发送给老板", senderUserName)
                // 发送接单说明书图片
                imagePath := "./image/peizhi/jiedan.jpg"
                fmt.Printf("准备发送图片: %s\n", imagePath)
                if imgFile, err := os.Open(imagePath); err == nil {
                    fmt.Println("成功打开接单说明书图片文件")
                    defer imgFile.Close()
                    if err := sendImage(imagePath, bridge.GroupID); err != nil {
                        fmt.Printf("发送图片失败: %v\n", err)
                    }
                    fmt.Println("已发送接单说明书图片")
                } else {
                    fmt.Println("没有找到接单说明书的图片文件")
                }
            } else if strings.HasPrefix(content, "铂金") || strings.HasPrefix(content, "钻石") || strings.HasPrefix(content, "星耀")|| strings.HasPrefix(content, "王者"){   
                progressContent := strings.Trim(content, "（）")       
                var finalRank sql.NullString
                err = db.QueryRow("SELECT FinalRank FROM Bridges WHERE ID = ?", bridge.ID).Scan(&finalRank)
                if err != nil {
                    fmt.Printf("查询桥接[%s]的最终段位失败：%v\n", bridge.ID, err)
                    return
                }
            
                ranksCosts, err := getAllRanksAndCosts(db)
                if err != nil {
                    fmt.Printf("获取所有段位和消耗信息失败：%v\n", err)
                    return
                }
            
                matchedPeak, nearestPeak := parsePeakRank(bridge.Msg)
                var peakBase int
                if matchedPeak != "" {
                    peakBase, _ = strconv.Atoi(matchedPeak[6:])
                }
                var initialRanks []string
                if finalRank.Valid && finalRank.String != "" {
                    _, finalNearestPeak := parsePeakRank(finalRank.String)
                    if finalNearestPeak != "" {
                        initialRanks = []string{finalNearestPeak}
                    } else {
                        initialRanks = []string{finalRank.String}
                    }
                } else if nearestPeak != "" {
                    initialRanks = []string{nearestPeak}
                } else {
                    sort.Slice(ranksCosts, func(i, j int) bool {
                        return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
                    })
                    for _, rankCost := range ranksCosts {
                        if strings.Contains(bridge.Msg, rankCost[0]) {
                            initialRanks = append(initialRanks, rankCost[0])
                            break
                        }
                    }
                }
                startIndex, err := getAdjustedRankOrder(initialRanks[0], db)
                if err != nil {
                    fmt.Printf("获取橙色标记的段位排序失败: %v\n", err)
                    return
                }
                orangeIndex, err := extractRankFromMessage(bridge.Msg, db)
                if err != nil {
                    fmt.Printf("解析消息中的初始段位失败: %v\n", err)
                    return
                }
                re := regexp.MustCompile(",最多打(\\d+)♥|,最多到(\\d+)")
                matches := re.FindStringSubmatch(bridge.Msg)
                var maxUpgrades int
                var finalTargetRank int
                if len(matches) > 1 {
                    for _, match := range matches[1:] {
                        if match != "" {
                            temp, _ := strconv.Atoi(match)
                            if strings.Contains(bridge.Msg, "最多到") {
                                finalTargetRank = temp
                                if peakBase > 0 {
                                    maxUpgrades = (finalTargetRank - peakBase) / 25
                                }
                            } else {
                                maxUpgrades = temp
                            }
                            break
                        }
                    }
                }
                orangeIndex += maxUpgrades
                var zuizhong string
                if !strings.Contains(progressContent, "巅峰") {
                    re := regexp.MustCompile(`^\d+$`)
                    if re.MatchString(progressContent) {
                        zuizhong = "巅峰" + progressContent
                    }
                }
            
                _, progressNearestPeak := parsePeakRank(zuizhong)
                if progressNearestPeak != "" {
                    progressContent = progressNearestPeak
                }

                endIndex, err := getAdjustedRankOrder(progressContent, db)
                if err != nil {
                    fmt.Printf("获取橙色标记的段位排序失败: %v\n", err)
                    return
                }
            
                if startIndex != -1 && endIndex != -1 {
                    upgradeCount := endIndex - startIndex
                    updateUserTotalStars(senderNickName, upgradeCount, bridge, 0)
                    _, err = db.Exec("UPDATE Bridges SET FinalRank = ? WHERE ID = ?", progressContent, bridge.ID)
                    if err != nil {
                        fmt.Printf("更新桥接[%s]的最终段位失败：%v\n", bridge.ID, err)
                    } else {
                        fmt.Printf("成功更新桥接[%s]的最终段位至[%s]\n", bridge.ID, progressContent)
                    }
                    if endIndex < orangeIndex {
                        var chaju int
                        chaju = orangeIndex - endIndex
                        sendTextMessage(fmt.Sprintf("已记录成功，距完单还差%d星，辛苦了，哥", chaju), senderUserName)

                    }
                    if endIndex >= orangeIndex {
                        forwardContent := fmt.Sprintf("@%s 您的订单已完成", bridge.GroupUserNickName)
                        sendTextMessage(forwardContent, bridge.GroupID)
                        sendTextMessage("已记录成功，您的订单已完成，发#完单，会自动结账", senderUserName)
                    }
                    _, totalStarsNeeded, err := getTargetRankAndPriceSum(db, initialRanks, upgradeCount)
                    if err != nil {
                        fmt.Printf("Error calculating target rank and stars: %v\n", err)
                        return
                    }
        
                    // 如果订单类型是"代练"，将星卷消耗除以2
                    if matchedPeak == "" {
                        totalStarsNeeded = (totalStarsNeeded + 1) / 2
                    }
                    // 在数据库中插入一条支出记录
                    insertExpenditureSQL := `INSERT INTO Expenditures (NickName, Payment, BridgeID) VALUES (?, ?, ?)`
                    _, err = db.Exec(insertExpenditureSQL, senderNickName, totalStarsNeeded, bridge.ID)
                    if err != nil {
                        fmt.Printf("Error inserting expenditure record: %v\n", err)
                        return
                    }
                    fmt.Printf("支付:%d", totalStarsNeeded)   
                    // 发送 HTTP 请求
                    data := PaymentData{
                        BridgeID:    bridge.ID,
                        Payment:     totalStarsNeeded,
                        Debtor:      senderNickName,
                        Creditor:    "国服车队联系员-梦乐",
                    }

                    jsonData, err := json.Marshal(data)
                    if err != nil {
                        fmt.Printf("Error marshaling data: %v\n", err)
                        return
                    }

                    url := "http://www.moki-flanke.icu:8080/api/payment" // 替换为实际的 API 路由
                    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
                    if err != nil {
                        fmt.Printf("Error creating request: %v\n", err)
                        return
                    }

                    req.Header.Set("Content-Type", "application/json")

                    client := &http.Client{}
                    resp, err := client.Do(req)
                    if err != nil {
                        fmt.Printf("Error sending request: %v\n", err)
                        return
                    }
                    defer resp.Body.Close()

                    if resp.StatusCode != http.StatusOK {
                        fmt.Printf("Error response from server: %v\n", resp.Status)
                    }

                    fmt.Println("请求已成功发送")  
                } else {
                    fmt.Println("进度计算错误或段位顺序不正确")
                }
            forwardContent := fmt.Sprintf("@%s %s", bridge.GroupUserNickName, content)
            sendTextMessage(forwardContent, bridge.GroupID)
            }       
        }
    }
}
func findBridgeByID(bridgeID string) (*Bridge, error) {
    var bridge Bridge
    err := db.QueryRow("SELECT * FROM Bridges WHERE ID = ?", bridgeID).Scan(
        &bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.GroupUserNickName, 
        &bridge.WeChatUser, &bridge.IsActive, &bridge.IsCompleted, &bridge.Msg, 
        &bridge.GameID, &bridge.Stars, &bridge.StarCost, &bridge.OrderType,
        &bridge.CreatedAt, &bridge.LastMessageTime, &bridge.FinalRank, &bridge.WeChatUsername, // 添加WeChatUsername
    )
    if err != nil {
        if err == sql.ErrNoRows {
            return nil, nil // 桥梁不存在
        }
        return nil, err // 数据库查询错误
    }
    return &bridge, nil
}
func findBridgeByWeChatUser(weChatUser string) (*Bridge, error) {
    log.Printf("Searching for bridge with WeChatUser: %s\n", weChatUser)
    
    var bridge Bridge
    query := `
        SELECT 
            ID, GroupID, GroupName, GroupUserNickName, WeChatUser, IsActive,
            IsCompleted, Msg, GameID, Stars, StarCost, OrderType,
            CreatedAt, LastMessageTime, FinalRank, WeChatUsername
        FROM Bridges
        WHERE WeChatUser = ? and IsActive = 1
        ORDER BY CreatedAt DESC 
        LIMIT 1
    `
    log.Printf("Executing query: %s\n", query)
    err := db.QueryRow(query, weChatUser).Scan(
        &bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.GroupUserNickName,
        &bridge.WeChatUser, &bridge.IsActive, &bridge.IsCompleted, &bridge.Msg,
        &bridge.GameID, &bridge.Stars, &bridge.StarCost, &bridge.OrderType,
        &bridge.CreatedAt, &bridge.LastMessageTime, &bridge.FinalRank, &bridge.WeChatUsername, // 添加WeChatUsername
    )
    if err != nil {
        if err == sql.ErrNoRows {
            log.Println("No active bridge found for the given WeChat user.")
            return nil, nil
        }
        log.Printf("Error scanning query result: %v\n", err)
        return nil, err
    }
    log.Printf("Found bridge: %+v\n", bridge)
    return &bridge, nil
}
func sendMessageToUser(username, orderID, messageType, messageContent string) {
    clientsMutex.RLock()
    defer clientsMutex.RUnlock()

    // 构造结构化消息
    msg := struct {
        OrderID string `json:"orderId"`
        Type    string `json:"type"`
        Content string `json:"content"`
    }{
        OrderID: orderID,
        Type:    messageType,
        Content: messageContent,
    }

    // 序列化为JSON
    jsonMsg, _ := json.Marshal(msg)

    // 遍历目标订单的所有连接
    if orderClients, exists := clients[orderID]; exists {
        for conn, client := range orderClients {
            // 匹配用户名
            if client.username == username {
                // 异步发送避免阻塞
                go func(c *websocket.Conn) {
                    if err := c.WriteMessage(websocket.TextMessage, jsonMsg); err != nil {
                        log.Printf("发送失败至用户 [%s]: %v", username, err)
                        c.Close()
                        clientsMutex.Lock()
                        delete(clients[orderID], conn)  // 正确删除连接指针为key的记录
                        clientsMutex.Unlock()
                    }
                }(conn)
            }
        }
    }
}

func sendMP3ToUser(username, orderID, mp3Path string) {
    // 读取MP3文件
    mp3Data, err := os.ReadFile(mp3Path)
    if err != nil {
        fmt.Printf("Error reading MP3 file: %v\n", err)
        return
    }

    // 将MP3数据编码为 Base64 字符串
    encodedMP3 := base64.StdEncoding.EncodeToString(mp3Data)

    // 发送MP3数据到用户，包含 orderID
    sendMessageToUser(username, orderID, "mp3", encodedMP3)
}

func sendImageToUser(username, orderID, imagePath string) {
    // 读取图片文件
    imageData, err := os.ReadFile(imagePath)
    if err != nil {
        fmt.Printf("Error reading image file: %v\n", err)
        return
    }

    // 将图片数据编码为 Base64 字符串
    encodedImage := base64.StdEncoding.EncodeToString(imageData)

    // 发送图片数据到用户，包含 orderID
    sendMessageToUser(username, orderID, "image", encodedImage)
}
func updateUserTotalStars(userNickName string, starsToAdd int, bridge *Bridge, multipleMatches int) {
    var currentTotalStars, currentCompleteOrderCount, currentBridgeCount int
    err := db.QueryRow("SELECT TotalStars, CompleteOrderCount, BridgeCount FROM user_stats WHERE NickName = ?", userNickName).Scan(&currentTotalStars, &currentCompleteOrderCount, &currentBridgeCount)
    if err != nil {
        if err == sql.ErrNoRows {
            fmt.Printf("No existing user stats found for user [%s]. Error: %v\n", userNickName, err)
            return
        } else {
            fmt.Printf("Error querying user stats for user [%s]. Error: %v\n", userNickName, err)
            return
        }
    }
    var finalRank sql.NullString
    var orderType string
    err = db.QueryRow("SELECT FinalRank, OrderType FROM Bridges WHERE ID = ?", bridge.ID).Scan(&finalRank,&orderType)
    if err != nil && err != sql.ErrNoRows {
        fmt.Printf("Error querying final rank for bridge [%s]: %v\n", bridge.ID, err)
        return
    }
    initialRanks := []string{}
    ranksAndPrices, err := getRanksAndPrices(db)
    if err != nil {
        fmt.Printf("Error getting ranks and prices: %v\n", err)
        return
    }
    
    // 对ranksAndPrices按照段位长度进行排序
    var ranks []string
    for rank := range ranksAndPrices {
        ranks = append(ranks, rank)
    }
    sort.Slice(ranks, func(i, j int) bool {
        return len(ranks[i]) > len(ranks[j])
    })
    containsPeak := strings.Contains(bridge.Msg, "巅峰")
    _, nearestPeak := parsePeakRank(bridge.Msg)
    if finalRank.Valid && finalRank.String != "" {
        _, finalNearestPeak := parsePeakRank(finalRank.String)
        if finalNearestPeak != "" {
            initialRanks = []string{finalNearestPeak}
        } else {
            initialRanks = strings.Split(finalRank.String, ",")
        }
    } else if nearestPeak != "" {
        initialRanks = []string{nearestPeak}
    } else {
        // 解析 bridge.Msg 来获取匹配的段位
        var matchedRanks []string
        input := bridge.Msg
        for _, rank := range ranks {
            rankOccurrences := strings.Count(input, rank)
            for i := 0; i < rankOccurrences; i++ {
                matchedRanks = append(matchedRanks, rank)
                input = strings.Replace(input, rank, "", 1)
            }
        }
        initialRanks = matchedRanks
    }
    finalRankString, totalStarsNeeded, err := getTargetRankAndStars(db, initialRanks, starsToAdd)
    if err != nil {
        fmt.Printf("Error calculating target rank and stars: %v\n", err)
        return
    }

    // 如果订单类型是"代练"，且没有涉及巅峰段位，则将星卷消耗减半
    if orderType == "代练" && !containsPeak {
        totalStarsNeeded /= 2
    }
    // 根据是否包含巅峰段位决定是否更新最终段位
    var updateQuery string
    if containsPeak {
        // 如果包含巅峰段位，则沿用上一次的最终段位进行更新
        updateQuery = "UPDATE Bridges SET StarCost = StarCost + ? WHERE ID = ?"
        _, err = db.Exec(updateQuery, totalStarsNeeded, bridge.ID)
    } else {
        // 如果不包含巅峰段位，更新最终段位及星卷消耗
        updateQuery = "UPDATE Bridges SET FinalRank = ?, StarCost = StarCost + ? WHERE ID = ?"
        _, err = db.Exec(updateQuery, finalRankString, totalStarsNeeded, bridge.ID)
    }
    if err != nil {
        fmt.Printf("Error updating final rank and star cost for bridge [%s]: %v\n", bridge.ID, err)
    } else {
        fmt.Printf("Successfully updated final rank to [%s] and star cost by [%d] for bridge [%s]\n", finalRankString, totalStarsNeeded, bridge.ID)
    }    
    // 更新用户的星卷数前的处理
    var frozenStars int

    fmt.Printf("Processing bridge with ID [%s] and GroupID [%s]\n", bridge.ID, bridge.GroupID)

    if bridge.GroupID == "网站" {
        // 查询冻结的星卷
        err := db.QueryRow("SELECT StarCost FROM StarFreeze WHERE ID = ?", bridge.ID).Scan(&frozenStars)
        if err != nil {
            if err == sql.ErrNoRows {
                frozenStars = 0 // 如果没有找到记录，则设为0
                fmt.Printf("No frozen stars found for bridge ID [%s]\n", bridge.ID)
            } else {
                fmt.Printf("Error querying frozen stars for bridge ID [%s]: %v\n", bridge.ID, err)
                return // 处理错误，必要时返回或采取其他措施
            }
        } else {
            fmt.Printf("Found frozen stars [%d] for bridge ID [%s]\n", frozenStars, bridge.ID)
        }
    } else {
        frozenStars = 0
        fmt.Printf("Bridge GroupID is not '网站', setting frozenStars to 0\n")
    }

    // 计算需要的总星卷数
    totalStarsToDeduct := totalStarsNeeded - frozenStars
    fmt.Printf("Total stars to deduct: %d (totalStarsNeeded: %d, frozenStars: %d)\n", totalStarsToDeduct, totalStarsNeeded, frozenStars)
    // 更新用户的星卷数
    if bridge.GroupID == "网站" {
        // 获取用户名和AI群
        var aiGroup, name string
        err := db.QueryRow("SELECT ai_group, name FROM users WHERE username = ?", bridge.GroupUserNickName).Scan(&aiGroup, &name)
        if err != nil {
            fmt.Printf("Error querying AI group: %v\n", err) // 打印错误信息
            return
        }

        if aiGroup == "" {
            // 如果没有AI群，更新用户表中的星卷数量
            _, err = db.Exec("UPDATE users SET star_journal = star_journal - ? WHERE username = ?", totalStarsToDeduct, bridge.GroupUserNickName)
            if err != nil {
                fmt.Printf("Error updating stars for user: %v\n", err) // 打印错误信息
            } else {
                fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bridge.GroupUserNickName, totalStarsToDeduct)
            }
        } else {
            // 更新群组中的星卷数量
            var existingStars int
            err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?", aiGroup, name).Scan(&existingStars)
            if err != nil && err != sql.ErrNoRows {
                fmt.Printf("Error querying existing stars: %v\n", err) // 打印错误信息
                return
            }

            if err == sql.ErrNoRows {
                // 插入新记录
                _, err = db.Exec("INSERT INTO member_stars (GroupID, UserName, StarsCount) VALUES (?, ?, ?)", aiGroup, name, -totalStarsToDeduct)
                if err != nil {
                    fmt.Printf("Error inserting new stars record: %v\n", err) // 打印错误信息
                } else {
                    fmt.Printf("Successfully inserted new stars record for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, totalStarsToDeduct)
                }
            } else {
                // 更新现有记录
                _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount - ? WHERE GroupID = ? AND UserName = ?", totalStarsToDeduct, aiGroup, name)
                if err != nil {
                    fmt.Printf("Error updating stars for group: %v\n", err) // 打印错误信息
                } else {
                    fmt.Printf("Successfully updated stars for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, totalStarsToDeduct)
                }
            }
        }

        // 删除冻结表中的记录
        _, err = db.Exec("DELETE FROM StarFreeze WHERE ID = ?", bridge.ID)
        if err != nil {
            fmt.Printf("Error deleting frozen stars for bridge ID [%s]: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Successfully deleted frozen stars for bridge ID [%s]\n", bridge.ID)
        }
    } else {
        // 更新其他用户的星卷数
        _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount - ? WHERE UserName = ? AND GroupID = ?", totalStarsToDeduct, bridge.GroupUserNickName, bridge.GroupName)
        if err != nil {
            fmt.Printf("Error updating stars for user [%s]: %v\n", bridge.GroupUserNickName, err)
        } else {
            fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bridge.GroupUserNickName, totalStarsToDeduct)
        }
    }

    newTotalStars := currentTotalStars + starsToAdd
    newCompleteOrderCount := currentCompleteOrderCount
    if multipleMatches > 1 && multipleMatches != newmultipleMatches{
        newCompleteOrderCount += 1
        bridge.IsCompleted = true
        newmultipleMatches = multipleMatches
        fmt.Printf("Complete order count incremented for user [%s]\n", userNickName)
        _, err = db.Exec("UPDATE Bridges SET IsCompleted = ? WHERE ID = ?", true, bridge.ID)
        if err != nil {
            fmt.Printf("Error updating bridge completion status for bridge [%s]. Error: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Bridge completion status updated for bridge [%s]\n", bridge.ID)
        }
    }
    // 桥梁未完成时，增加完单计数并更新桥梁状态
    if !bridge.IsCompleted && starsToAdd >= 1 {
        newCompleteOrderCount += 1
        _, err = db.Exec("UPDATE Bridges SET IsCompleted = 1 WHERE ID = ?", bridge.ID)
        if err != nil {
            fmt.Printf("Error marking bridge [%s] as completed: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Bridge [%s] marked as completed.\n", bridge.ID)
            bridge.IsCompleted = true // 在内存中更新桥梁状态
        }
    }

    // 更新用户统计数据
    _, err = db.Exec("UPDATE user_stats SET TotalStars = ?, CompleteOrderCount = ? WHERE NickName = ?", newTotalStars, newCompleteOrderCount, userNickName)
    if err != nil {
        fmt.Printf("Error updating user stats for [%s]: %v\n", userNickName, err)
    } else {
        fmt.Printf("User stats updated for [%s]. Total stars: %d, Complete order count: %d\n", userNickName, newTotalStars, newCompleteOrderCount)
    }

    // 插入 UnsettledBridges 表的记录
    result, err := db.Exec("UPDATE UnsettledBridges SET Stars = Stars + ?, Msg = ?, SettlementTime = datetime('now') WHERE ID = ?",
    starsToAdd, bridge.Msg, bridge.ID)

    if err != nil {
    fmt.Printf("Error updating UnsettledBridges: %v\n", err)
    return
    }

    rowsAffected, _ := result.RowsAffected()
    if rowsAffected == 0 {
    // 如果没有更新任何记录，说明没有找到匹配的 ID，需要插入新记录
    _, err = db.Exec("INSERT INTO UnsettledBridges (ID, WeChatUser, GameID, Stars, Msg, SettlementTime) VALUES (?, ?, ?, ?, ?, datetime('now'))",
        bridge.ID, userNickName, bridge.GameID, starsToAdd, bridge.Msg)
    if err != nil {
        fmt.Printf("Error inserting into UnsettledBridges: %v\n", err)
    }
    }
}
func updateUserTotalStars1(userNickName string, starsToAdd int, bridge *Bridge, multipleMatches int) {
    var currentTotalStars, currentCompleteOrderCount, currentBridgeCount int
    err := db.QueryRow("SELECT TotalStars, CompleteOrderCount, BridgeCount FROM user_stats WHERE NickName = ?", userNickName).Scan(&currentTotalStars,
         &currentCompleteOrderCount, &currentBridgeCount)
    if err != nil {
        if err == sql.ErrNoRows {
            fmt.Printf("No existing user stats found for user [%s]. Error: %v\n", userNickName, err)
            return
        } else {
            fmt.Printf("Error querying user stats for user [%s]. Error: %v\n", userNickName, err)
            return
        }
    }

    if bridge.GroupName != "代发" {
        // 星卷相关逻辑开始
        var effectiveStarCost, currentStars int
        var starCost, stars sql.NullInt64
        var orderType string

        err = db.QueryRow("SELECT OrderType, StarCost, Stars FROM Bridges WHERE ID = ?", bridge.ID).Scan(&orderType, &starCost, &stars)
        if err != nil && err != sql.ErrNoRows {
            fmt.Printf("Error querying final rank for bridge [%s]: %v\n", bridge.ID, err)
            return
        }
        if !starCost.Valid {
            effectiveStarCost = 0
            fmt.Printf("starCost is invalid, setting effectiveStarCost to 0\n")
        } else {
            effectiveStarCost = int(starCost.Int64)
            fmt.Printf("starCost is valid, setting effectiveStarCost to %d\n", effectiveStarCost)
        }

        if stars.Valid {
            currentStars = int(stars.Int64)
        } else {
            currentStars = 0
        }
        currentTotalStars = currentTotalStars + starsToAdd - currentStars
        initialRanks := []string{}
        ranksAndPrices, err := getRanksAndPrices(db)
        if err != nil {
            fmt.Printf("Error getting ranks and prices: %v\n", err)
            return
        }

        // 对 ranksAndPrices 按照段位长度进行排序
        var ranks []string
        for rank := range ranksAndPrices {
            ranks = append(ranks, rank)
        }
        sort.Slice(ranks, func(i, j int) bool {
            return len(ranks[i]) > len(ranks[j])
        })
        containsPeak := strings.Contains(bridge.Msg, "巅峰")
        _, nearestPeak := parsePeakRank(bridge.Msg)
        if nearestPeak != "" {
            initialRanks = []string{nearestPeak}
        } else {
            var matchedRanks []string
            input := bridge.Msg
            for _, rank := range ranks {
                rankOccurrences := strings.Count(input, rank)
                for i := 0; i < rankOccurrences; i++ {
                    matchedRanks = append(matchedRanks, rank)
                    input = strings.Replace(input, rank, "", 1)
                }
            }
            initialRanks = matchedRanks
        }
        finalRankString, totalStarsNeeded, err := getTargetRankAndStars(db, initialRanks, starsToAdd)
        if err != nil {
            fmt.Printf("Error calculating target rank and stars: %v\n", err)
            return
        }

        if orderType == "代练" && !containsPeak {
            totalStarsNeeded /= 2
        }

        var updateQuery string
        if containsPeak {
            updateQuery = "UPDATE Bridges SET StarCost = ? WHERE ID = ?"
            _, err = db.Exec(updateQuery, totalStarsNeeded, bridge.ID)
        } else {
            updateQuery = "UPDATE Bridges SET FinalRank = ?, StarCost = ? WHERE ID = ?"
            _, err = db.Exec(updateQuery, finalRankString, totalStarsNeeded, bridge.ID)
        }
        if err != nil {
            fmt.Printf("Error updating final rank and star cost for bridge [%s]: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Successfully updated final rank to [%s] and star cost by [%d] for bridge [%s]\n", finalRankString, totalStarsNeeded, bridge.ID)
        }

        var frozenStars int
        if bridge.GroupID == "网站" {
            err := db.QueryRow("SELECT StarCost FROM StarFreeze WHERE ID = ?", bridge.ID).Scan(&frozenStars)
            if err != nil {
                if err == sql.ErrNoRows {
                    frozenStars = 0
                    fmt.Printf("No frozen stars found for bridge ID [%s], setting frozenStars to 0\n", bridge.ID)
                } else {
                    fmt.Printf("Error querying frozen stars for bridge ID [%s]: %v\n", bridge.ID, err)
                    return
                }
            } else {
                fmt.Printf("Found frozen stars [%d] for bridge ID [%s]\n", frozenStars, bridge.ID)
            }
        } else {
            frozenStars = 0
            fmt.Printf("Bridge GroupID is not '网站', setting frozenStars to 0\n")
        }

        totalStarsToDeduct := totalStarsNeeded - effectiveStarCost - frozenStars
        fmt.Printf("Total stars to deduct: %d (totalStarsNeeded: %d, effectiveStarCost: %d, frozenStars: %d)\n", totalStarsToDeduct, totalStarsNeeded, effectiveStarCost, frozenStars)

        if bridge.GroupID == "网站" {
            var aiGroup, name string
            err := db.QueryRow("SELECT ai_group, name FROM users WHERE username = ?", bridge.GroupUserNickName).Scan(&aiGroup, &name)
            if err != nil {
                fmt.Printf("Error querying AI group: %v\n", err)
                return
            }

            if aiGroup == "" {
                _, err = db.Exec("UPDATE users SET star_journal = star_journal - ? WHERE username = ?", totalStarsToDeduct, bridge.GroupUserNickName)
                if err != nil {
                    fmt.Printf("Error updating stars for user: %v\n", err)
                } else {
                    fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bridge.GroupUserNickName, totalStarsToDeduct)
                }
            } else {
                var existingStars int
                err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?", aiGroup, name).Scan(&existingStars)
                if err != nil && err != sql.ErrNoRows {
                    fmt.Printf("Error querying existing stars: %v\n", err)
                    return
                }

                if err == sql.ErrNoRows {
                    _, err = db.Exec("INSERT INTO member_stars (GroupID, UserName, StarsCount) VALUES (?, ?, ?)", aiGroup, name, -totalStarsToDeduct)
                    if err != nil {
                        fmt.Printf("Error inserting new stars record: %v\n", err)
                    } else {
                        fmt.Printf("Successfully inserted new stars record for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, totalStarsToDeduct)
                    }
                } else {
                    _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount - ? WHERE GroupID = ? AND UserName = ?", totalStarsToDeduct, aiGroup, name)
                    if err != nil {
                        fmt.Printf("Error updating stars for group: %v\n", err)
                    } else {
                        fmt.Printf("Successfully updated stars for user [%s] in group [%s], deducted stars: %d\n", name, aiGroup, totalStarsToDeduct)
                    }
                }
            }

            _, err = db.Exec("DELETE FROM StarFreeze WHERE ID = ?", bridge.ID)
            if err != nil {
                fmt.Printf("Error deleting frozen stars for bridge ID [%s]: %v\n", bridge.ID, err)
            } else {
                fmt.Printf("Successfully deleted frozen stars for bridge ID [%s]\n", bridge.ID)
            }
        } else {
            _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount - ? WHERE UserName = ? AND GroupID = ?", totalStarsToDeduct, bridge.GroupUserNickName, bridge.GroupName)
            if err != nil {
                fmt.Printf("Error updating stars for user [%s]: %v\n", bridge.GroupUserNickName, err)
            } else {
                fmt.Printf("Successfully updated stars for user [%s], deducted stars: %d\n", bridge.GroupUserNickName, totalStarsToDeduct)
            }
        }
        // 星卷相关逻辑结束
    }

    // 剩余的订单完成计数逻辑保持不变
    newCompleteOrderCount := currentCompleteOrderCount
    if multipleMatches > 1 {
        newCompleteOrderCount += 1
        bridge.IsCompleted = true
        fmt.Printf("Complete order count incremented for user [%s]\n", userNickName)
        _, err = db.Exec("UPDATE Bridges SET IsCompleted = ? WHERE ID = ?", true, bridge.ID)
        if err != nil {
            fmt.Printf("Error updating bridge completion status for bridge [%s]. Error: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Bridge completion status updated for bridge [%s]\n", bridge.ID)
        }
    }
    if !bridge.IsCompleted && starsToAdd >= 1 {
        newCompleteOrderCount += 1
        _, err = db.Exec("UPDATE Bridges SET IsCompleted = 1 WHERE ID = ?", bridge.ID)
        if err != nil {
            fmt.Printf("Error marking bridge [%s] as completed: %v\n", bridge.ID, err)
        } else {
            fmt.Printf("Bridge [%s] marked as completed.\n", bridge.ID)
            bridge.IsCompleted = true
        }
    }

    _, err = db.Exec("UPDATE user_stats SET TotalStars = ?, CompleteOrderCount = ? WHERE NickName = ?", currentTotalStars, newCompleteOrderCount, userNickName)
    if err != nil {
        fmt.Printf("Error updating user stats for [%s]: %v\n", userNickName, err)
    } else {
        fmt.Printf("User stats updated for [%s]. Total stars: %d, Complete order count: %d\n", userNickName, currentTotalStars, newCompleteOrderCount)
    }

    result, err := db.Exec("UPDATE UnsettledBridges SET Stars = ?, Msg = ?, SettlementTime = datetime('now') WHERE ID = ?", starsToAdd, bridge.Msg, bridge.ID)
    if err != nil {
        fmt.Printf("Error updating UnsettledBridges: %v\n", err)
        return
    }

    rowsAffected, _ := result.RowsAffected()
    if rowsAffected == 0 {
        _, err = db.Exec("INSERT INTO UnsettledBridges (ID, WeChatUser, GameID, Stars, Msg, SettlementTime) VALUES (?, ?, ?, ?, ?, datetime('now'))",
            bridge.ID, userNickName, bridge.GameID, starsToAdd, bridge.Msg)
        if err != nil {
            fmt.Printf("Error inserting into UnsettledBridges: %v\n", err)
        }
    }
}
func getTargetRankAndPriceSum(db *sql.DB, initialRanks []string, updateCount int) (string, int, error) {
    ranksCosts, err := getAllRanksAndPrices(db)
    if err != nil {
        return "", 0, err
    }

    totalStarsConsumed := 0
    finalRanks := ""

    for _, initialRank := range initialRanks {
        rankIndex := -1
        for i, pair := range ranksCosts {
            if pair[0] == initialRank {
                rankIndex = i
                break
            }
        }

        if rankIndex == -1 {
            return "", 0, fmt.Errorf("invalid rank: %s", initialRank)
        }

        starsForCurrentRank := 0
        currentRank := initialRank

        if updateCount >= 0 {
            // 处理升级逻辑
            for i := 0; i < updateCount && rankIndex+1 < len(ranksCosts); i++ {
                starCost, err := strconv.Atoi(ranksCosts[rankIndex][1])
                if err != nil {
                    return "", 0, fmt.Errorf("invalid star cost for rank %s: %s", ranksCosts[rankIndex+1][0], ranksCosts[rankIndex+1][1])
                }
                starsForCurrentRank += starCost
                currentRank = ranksCosts[rankIndex+1][0]
                rankIndex++
            }
        } else {
            // 处理降级逻辑
            for i := 0; i < -updateCount && rankIndex-1 >= 0; i++ {
                starCost, err := strconv.Atoi(ranksCosts[rankIndex][1])
                if err != nil {
                    return "", 0, fmt.Errorf("invalid star cost for rank %s: %s", ranksCosts[rankIndex-1][0], ranksCosts[rankIndex-1][1])
                }
                starsForCurrentRank -= starCost  // 降级时减少星卷消耗
                currentRank = ranksCosts[rankIndex-1][0]
                rankIndex--
            }
        }

        totalStarsConsumed += starsForCurrentRank
        finalRanks += currentRank + ","  // 更新段位字符串
    }

    if len(finalRanks) > 0 {
        finalRanks = finalRanks[:len(finalRanks)-1]  // 移除最后一个逗号
    }

    return finalRanks, totalStarsConsumed, nil
}
func getAdjustedRankOrder(rank string, db *sql.DB) (int, error) {
    var rankOrder int
    // 检查是否为"巅峰"段位
    if strings.Contains(rank, "巅峰") {
        // 直接查询数据库中的排序值
        err := db.QueryRow("SELECT RankOrder FROM RankPrices WHERE Rank = ?", rank).Scan(&rankOrder)
        if err != nil {
            return 0, fmt.Errorf("无法获取段位 %s 的排序: %v", rank, err)
        }
        return rankOrder, nil
    } else {
        // 对于非"巅峰"段位，使用原有逻辑处理
        err := db.QueryRow("SELECT RankOrder FROM RankPrices WHERE Rank = ?", rank).Scan(&rankOrder)
        if err != nil {
            return 0, fmt.Errorf("无法获取段位 %s 的排序: %v", rank, err)
        }
        for rankOrder >= 167 {
            rankOrder -= 166
        }
        return rankOrder, nil
    }
}
func extractRankFromMessage(content string, db *sql.DB) (int, error) {
    ranksAndPrices, err := getRanksAndPrices(db)
    if err != nil {
        return 0, fmt.Errorf("error getting ranks and prices: %v", err)
    }

    // 首先尝试解析巅峰段位
    _, nearestPeak := parsePeakRank(content)
    if nearestPeak != "" {
        return getAdjustedRankOrder(nearestPeak, db)
    }

    var ranks []string
    for rank := range ranksAndPrices {
        ranks = append(ranks, rank)
    }

    // 按长度降序排序，确保最长的段位排在前面
    sort.Slice(ranks, func(i, j int) bool {
        return len(ranks[i]) > len(ranks[j])
    })

    var longestMatchedRank string
    var foundMatch bool
    // 从最长的段位开始检查，找到第一个匹配的段位
    for _, rank := range ranks {
        if strings.Contains(content, rank) {
            if foundMatch {
                return 0, fmt.Errorf("multiple ranks matched in the message")
            }
            longestMatchedRank = rank
            foundMatch = true
            // 从内容中移除第一个找到的匹配段位，准备检查是否还有其他匹配
            content = strings.Replace(content, rank, "", 1)
        }
    }

    if foundMatch {
        // 再次扫描看是否还有剩余的匹配项
        for _, rank := range ranks {
            if strings.Contains(content, rank) {
                return 0, fmt.Errorf("multiple ranks matched in the message after initial match removal")
            }
        }
        // 如果只有一个匹配，处理这个段位
        return getAdjustedRankOrder(longestMatchedRank, db)
    }

    return 0, fmt.Errorf("no rank matched in the message")
}

func getTargetRankAndStars(db *sql.DB, initialRanks []string, updateCount int) (string, int, error) {
    ranksCosts, err := getAllRanksAndCosts(db)
    if err != nil {
        return "", 0, err
    }

    totalStarsConsumed := 0
    finalRanks := ""

    for _, initialRank := range initialRanks {
        rankIndex := -1
        for i, pair := range ranksCosts {
            if pair[0] == initialRank {
                rankIndex = i
                break
            }
        }

        if rankIndex == -1 {
            return "", 0, fmt.Errorf("invalid rank: %s", initialRank)
        }

        starsForCurrentRank := 0
        currentRank := initialRank

        if updateCount >= 0 {
            // 处理升级逻辑
            for i := 0; i < updateCount && rankIndex+1 < len(ranksCosts); i++ {
                starCost, err := strconv.Atoi(ranksCosts[rankIndex][1])
                if err != nil {
                    return "", 0, fmt.Errorf("invalid star cost for rank %s: %s", ranksCosts[rankIndex][0], ranksCosts[rankIndex][1])
                }
                starsForCurrentRank += starCost
                currentRank = ranksCosts[rankIndex+1][0]
                rankIndex++
            }
        } else {
            // 处理降级逻辑
            for i := 0; i < -updateCount && rankIndex-1 >= 0; i++ {
                starCost, err := strconv.Atoi(ranksCosts[rankIndex][1])
                if err != nil {
                    return "", 0, fmt.Errorf("invalid star cost for rank %s: %s", ranksCosts[rankIndex][0], ranksCosts[rankIndex-1][1])
                }
                starsForCurrentRank -= starCost  // 降级时减少星卷消耗
                currentRank = ranksCosts[rankIndex-1][0]
                rankIndex--
            }
        }

        totalStarsConsumed += starsForCurrentRank
        finalRanks += currentRank + ","  // 更新段位字符串
    }

    if len(finalRanks) > 0 {
        finalRanks = finalRanks[:len(finalRanks)-1]  // 移除最后一个逗号
    }

    return finalRanks, totalStarsConsumed, nil
}

func getAllRanksAndPrices(db *sql.DB) ([][2]string, error) {
    var ranksPrices [][2]string

    // 确保查询结果按照RankOrder排序
    query := "SELECT Rank, Price FROM RankPrices ORDER BY RankOrder ASC"
    rows, err := db.Query(query)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    for rows.Next() {
        var rank string
        var price int
        if err := rows.Scan(&rank, &price); err != nil {
            continue // 处理错误
        }
        ranksPrices = append(ranksPrices, [2]string{rank, strconv.Itoa(price)})
    }

    if err = rows.Err(); err != nil {
        return nil, err
    }

    return ranksPrices, nil
}
func checkActiveTracking(db *sql.DB, senderUserName string) (*RankTracking, error) {
    var tracking RankTracking
    err := db.QueryRow("SELECT StarredUser, WaitingFor, Active FROM RankTrackings WHERE WaitingFor = ?", senderUserName).Scan(
        &tracking.StarredUser, &tracking.WaitingFor, &tracking.Active)
    if err != nil {
        if err == sql.ErrNoRows {
            return nil, nil // 没有匹配的活跃跟踪
        }
        return nil, err
    }
    return &tracking, nil
}
func handleUnsettledRecords(weChatUser string, db *sql.DB) {
    // 查询未结账记录以及可能的支付金额，确保记录唯一
    rows, err := db.Query(`
    SELECT DISTINCT u.WeChatUser, u.ID, u.GameID, u.Stars, u.Msg, COALESCE(SUM(e.Payment), 0) AS Payment
    FROM UnsettledBridges u
    LEFT JOIN Expenditures e ON u.ID = e.BridgeID
    WHERE u.WeChatUser = ? AND u.IsSettled = 0
    GROUP BY u.ID, u.WeChatUser, u.GameID, u.Stars, u.Msg
    ORDER BY u.SettlementTime DESC`, weChatUser)

    if err != nil {
        fmt.Printf("查询未结账记录失败: %v\n", err)
        return
    }
    defer rows.Close()

    // 创建一个map来记录每个BridgeID对应的所有stars
    bridgeStars := make(map[string][]int)
    // 创建一个map来记录每个BridgeID对应的其它信息（以第一次遇到的记录为准）
    bridgeInfo := make(map[string]string)

    // 首先收集数据
    for rows.Next() {
        var weChatUser, gameID, msg, bridgeID string
        var stars, payment int
        err := rows.Scan(&weChatUser, &bridgeID, &gameID, &stars, &msg, &payment)
        if err != nil {
            fmt.Printf("读取未结账记录失败: %v\n", err)
            continue
        }

        // 将stars添加到对应的BridgeID下
        bridgeStars[bridgeID] = append(bridgeStars[bridgeID], stars)

        // 只记录第一次遇到的BridgeID的其它信息
        if _, exists := bridgeInfo[bridgeID]; !exists {
            var unsettledMsg string
            unsettledMsg = fmt.Sprintf("用户：%s\n支付金额：%d\n订单信息：%s\n游戏ID：%s", weChatUser, payment, msg, gameID)
            bridgeInfo[bridgeID] = unsettledMsg
        }
    }

    // 现在发送消息
    for bridgeID, info := range bridgeInfo {
        starsArray := bridgeStars[bridgeID]
        starsText := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(starsArray)), "+"), "[]")

        // 拼接stars信息到消息中
        message := fmt.Sprintf("%s\n星数：%s", info, starsText)
        sendTextMessage(message, "moki-flanke")
    }
}
func updateTrackingActivity(db *sql.DB, starredUser string, isActive bool, isGroupChatActive bool) error {
    _, err := db.Exec("UPDATE RankTrackings SET Active = ?, GroupChatActive = ? WHERE StarredUser = ?", isActive, isGroupChatActive, starredUser)
    if err != nil {
        return fmt.Errorf("error updating tracking activity: %w", err)
    }
    return nil
}

func positionMatches(content, position string) bool {
    positionAliases := map[string][]string{
        "野": {"打野", "野", "刺客"},
        "中": {"法师", "中路", "法", "中"},
        "边": {"边路", "对抗", "边"},
        "射": {"射手", "发育", "射"},
        "辅": {"辅助", "游走", "辅"},
    }

    // 将位置字符串分解为单个字符，每个字符代表一个位置
    positions := strings.Split(position, "")

    // 检查消息内容是否包含任何一个位置的别名
    for _, pos := range positions {
        if aliases, ok := positionAliases[pos]; ok {
            for _, alias := range aliases {
                if strings.Contains(content, alias) {
                    return true
                }
            }
        }
    }
    return false
}

func UpdateTrackingStatus(db *sql.DB, starredUser string, waitingFor string, groupChatActive bool) error {
    _, err := db.Exec("UPDATE RankTrackings SET WaitingFor = ?, GroupChatActive = ? WHERE StarredUser = ?", waitingFor, groupChatActive, starredUser)
    if err != nil {
        return fmt.Errorf("error updating tracking status: %w", err)
    }
    return nil
}

func incrementCompleteOrderCount(userNickName string, db *sql.DB) error {
    query := "UPDATE user_stats SET CompleteOrderCount = CompleteOrderCount + 1 WHERE NickName = ?"
    _, err := db.Exec(query, userNickName)
    if err != nil {
        return fmt.Errorf("无法增加完单数量: %v", err)
    }
    return nil
}

func clearWeChatUserFromActiveBridges(weChatUser string, db *sql.DB) error {
    // 先找到最新创建的活跃桥接
    query := `SELECT ID, GroupUserNickName, GroupID FROM Bridges WHERE WeChatUser = ? AND IsActive = 1 ORDER BY CreatedAt DESC LIMIT 1`
    
    // 用来存储桥接ID的变量
    var latestBridgeID, groupUserNickName, groupID string
    // 执行查询
    err := db.QueryRow(query, weChatUser).Scan(&latestBridgeID, &groupUserNickName, &groupID)
    if err != nil {
        if err == sql.ErrNoRows {
            // 没有找到记录，可能不需要更新
            return nil
        }
        // 查询过程中发生了错误
        return err
    }
        // 如果找到了群昵称和群ID，则通知群内成员需要建立新的桥梁
    if groupUserNickName != "" && groupID != "" {
        groupMessage := fmt.Sprintf("@%s，乖乖！车队路上被碰瓷了！耐心等待！", groupUserNickName)
        sendTextMessage(groupMessage, groupID)
    }

    // 如果找到了最新的桥接，更新WeChatUser字段为空
    if latestBridgeID != "" {
        updateStmt := `UPDATE Bridges SET WeChatUser = '' WHERE ID = ?`
        _, err = db.Exec(updateStmt, latestBridgeID)
        if err != nil {
            // 更新过程中发生了错误
            return err
        }
    }
    
    return nil
}
// Check if the user is on the blacklist.
func isUserBlacklisted(db *sql.DB, nickname string) (bool, error) {
    var exists int
    // 使用 CONCAT 来确保分隔符在匹配字符串的两侧
    query := "SELECT COUNT(*) FROM current_event WHERE event_text LIKE CONCAT('%|', ?, '|%') AND id = 10"
    err := db.QueryRow(query, nickname).Scan(&exists)
    if err != nil {
        return false, err
    }
    return exists > 0, nil
}
func findBridgeForContent(content string) (*Bridge, error) {
    var bridge Bridge
    err := db.QueryRow(`
        SELECT 
            ID, GroupID, GroupName, GroupUserNickName,
            WeChatUser, IsActive, IsCompleted, Msg,
            GameID, COALESCE(NULLIF(Stars, ''), '0') AS Stars, 
            COALESCE(NULLIF(StarCost, ''), '0') AS StarCost, 
            OrderType, CreatedAt, LastMessageTime, FinalRank, WeChatUsername
        FROM Bridges 
        WHERE Msg = ? AND IsActive = 1
        ORDER BY CreatedAt DESC
        LIMIT 1`, // 添加LIMIT 1确保只获取一个结果
        content,
    ).Scan(
        &bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.GroupUserNickName,
        &bridge.WeChatUser, &bridge.IsActive, &bridge.IsCompleted, &bridge.Msg,
        &bridge.GameID, &bridge.Stars, &bridge.StarCost, &bridge.OrderType,
        &bridge.CreatedAt, &bridge.LastMessageTime, &bridge.FinalRank, &bridge.WeChatUsername, // 添加WeChatUsername
    )
    if err != nil {
        if err == sql.ErrNoRows {
            return nil, nil // No bridge found
        }
        return nil, err
    }
    return &bridge, nil
}
func updateBridgeWithWeChatUser(bridge *Bridge, weChatUserName, senderNickName string) error {
    orderType := bridge.OrderType
    
    _, err := db.Exec(`
        UPDATE Bridges SET 
            WeChatUser = ?,
            WeChatUsername = ?, 
            IsActive = 1
        WHERE ID = ?
    `, senderNickName, weChatUserName, bridge.ID)
    
    fmt.Printf("桥梁已更新，微信用户 [%s] 昵称 [%s] 与群内成员 [%s] 关联\n", weChatUserName, senderNickName, bridge.GroupUserNickName)
    updateUserStatsOnBridgeAssociation(senderNickName, bridge.GroupName)

    danhao := "#" + bridge.ID + "："
    var nihao string

    // 查询 Bridge 表中的 Msg
    var bridgeMsg string
    err = db.QueryRow("SELECT Msg FROM Bridges WHERE ID = ?", bridge.ID).Scan(&bridgeMsg)
    if err != nil {
        fmt.Printf("Error querying bridge Msg: %v\n", err)
        return err
    }

    if gameID, exists := globalGameIDMap[bridgeMsg]; exists {
        if bridge.GroupName == "代发" {
            updateBridgeMessageHistory(bridge.ID, gameID)
            
            // 从全局map中查找对应的联系人wxid
            contactUserName, exists := globalMessageContactMap[bridgeMsg]
            if !exists {
                // 没有找到对应的联系人信息，发送原始消息
                sendTextMessage("您已成功接手订单，下面是老板ID", weChatUserName)
                sendTextMessage(gameID, weChatUserName)
                sendTextMessage(fmt.Sprintf("上面就是老板id，私加老板老板举报免单，https://www.moki-flanke.icu/hitt/%s，点击链接进行交流结账", bridge.ID), weChatUserName)
                delete(globalGameIDMap, bridgeMsg)
            } else {
                // 找到对应的联系人wxid，发送更新的消息并发送名片
                sendTextMessage("您已成功接手订单，下面是老板ID", weChatUserName)
                sendTextMessage(gameID, weChatUserName)
                sendTextMessage(fmt.Sprintf("上面就是老板id，私加老板老板举报免单，https://www.moki-flanke.icu/hitt/%s，这是代发单子，联系不上找下方名片", bridge.ID), weChatUserName)
                
                // 发送联系人名片
                sendContactCard(contactUserName, weChatUserName)
                delete(globalGameIDMap, bridgeMsg)
                // 从联系人映射中删除
                delete(globalMessageContactMap, bridgeMsg)
            }
            
            delete(globalGameIDMap, bridgeMsg)
        } else {
            // 情况2：msg 存在于 globalGameIDMap 但 GroupName 不是 "代发"
            updateBridgeMessageHistory(bridge.ID, gameID)
            nihao = danhao + "您好！加你了，同意一下"
            sendTextMessage("您已成功接手订单，下面是老板ID", weChatUserName)
            sendTextMessage(gameID, weChatUserName)
            sendTextMessage(fmt.Sprintf("上面就是老板id，私加老板老板举报免单，https://www.moki-flanke.icu/hitt/%s，点击链接进行交流结账", bridge.ID), weChatUserName)
            sendTextMessage(nihao, weChatUserName)
            delete(globalGameIDMap, bridgeMsg)
        }
    } else {
        // 情况3：msg 不存在于 globalGameIDMap
        sendTextMessage("您已成功接手订单，耐心等待...", weChatUserName)
        sendTextMessage(fmt.Sprintf("https://www.moki-flanke.icu/hitt/%s", bridge.ID), weChatUserName)
        sendTextMessage("点击上方链接进行交流结账", weChatUserName)
    }
    if bridge.GroupName != "网站" {  
        if orderType == "代练" {
            nihao = danhao + "您好！现在准备扫码"
            groupMessage := fmt.Sprintf("@%s 叮！来咯！有大神来了！麻烦提前准备好扫码", bridge.GroupUserNickName)
            sendTextMessage(groupMessage, bridge.GroupID)
            sendTextMessage(nihao, weChatUserName)
        } else if bridge.GroupName != "代发"{
            groupMessage := fmt.Sprintf("@%s 叮！来咯！有大腿儿了！告诉我你的名字，#id，复制就行", bridge.GroupUserNickName)
            sendTextMessage(groupMessage, bridge.GroupID)
        }
    }
    
    if err != nil {
        fmt.Printf("Error updating bridge with wechat user: %v\n", err)
    }
    _, err = db.Exec(`
        INSERT INTO friends (userName, nickName) 
        VALUES (?, ?)
        ON CONFLICT(userName) DO UPDATE SET 
            nickName = excluded.nickName
    `, weChatUserName, senderNickName)
    
    if err != nil {
        fmt.Printf("好友信息操作失败 | 微信用户:%s | 错误:%v\n", weChatUserName, err)
        // 根据业务需求决定是否返回错误
        // return err
    } else {
        fmt.Printf("好友信息已更新 | 微信用户:%s | 昵称:%s\n", weChatUserName, senderNickName)
    }
    return err
}
func getAccessToken() (string, error) {
    url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appID, appSecret)
    resp, err := http.Get(url)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return "", err
    }

    accessToken, ok := result["access_token"].(string)
    if !ok {
        return "", fmt.Errorf("Failed to get access_token: %v", result)
    }

    return accessToken, nil
}
func sendTemplateMessage(accessToken string, message TemplateMessage) error {
    url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken)

    // 序列化消息结构体为 JSON
    requestBody, err := json.Marshal(message)
    if err != nil {
        return err
    }

    // 发起 POST 请求
    resp, err := http.Post(url, "application/json", bytes.NewReader(requestBody))
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    // 检查响应状态码
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
    }

    // 可以根据需要处理响应结果，这里简单打印响应内容
    var result map[string]interface{}
    err = json.NewDecoder(resp.Body).Decode(&result)
    if err != nil {
        return err
    }

    fmt.Println("Response:", result)

    return nil
}
// 获取小程序 accessToken 的函数
func getMiniAccessToken() (string, error) {
	// 小程序的 appID 和 appSecret
	appID := "wx86cbc2487aeab9fd"       // 替换为你的小程序 appID
	appSecret := "70cf597a7a577253071407db03f7ba6f"  // 替换为你的小程序 appSecret

	// 构建请求 URL
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appID, appSecret)

	// 发送 HTTP GET 请求
	resp, err := http.Get(url)
	if err != nil {
		return "", fmt.Errorf("请求微信 accessToken 接口失败: %v", err)
	}
	defer resp.Body.Close()

	// 解析响应
	var result struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
		ErrCode     int    `json:"errcode"`
		ErrMsg      string `json:"errmsg"`
	}

	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return "", fmt.Errorf("解析微信 accessToken 接口响应失败: %v", err)
	}

	// 检查是否返回错误
	if result.ErrCode != 0 {
		return "", fmt.Errorf("获取 accessToken 失败: %s", result.ErrMsg)
	}

	// 返回新的 accessToken
	fmt.Println("成功获取新的 accessToken:", result.AccessToken)
	return result.AccessToken, nil
}
func sendSubscribeMessage(accessToken string, message map[string]interface{}) error {
    url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", accessToken)

    jsonData, err := json.Marshal(message)
    if err != nil {
        return err
    }

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    if err != nil {
        return err
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    var result struct {
        ErrCode int    `json:"errcode"`
        ErrMsg  string `json:"errmsg"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return err
    }

    if result.ErrCode != 0 {
        return fmt.Errorf("failed to send subscribe message: %s", result.ErrMsg)
    }
    return nil
}
func processNumericResponse(content string, fromUserName string, senderNickName string) {
    allBridges, err := findAllBridgesForWeChatUser(senderNickName)
    if err != nil {
        fmt.Printf("Error finding bridges for user [%s]. Error: %v\n", senderNickName, err)
        return
    }
    // 按 CreatedAt 降序排序 allBridges，确保最新创建的 Bridge 位于前面
    sort.Slice(allBridges, func(i, j int) bool {
        return allBridges[i].CreatedAt.After(allBridges[j].CreatedAt)
    })
    var payment int
    var foundMatches int
    var gameID string
    var starsToAdd int
    var lastMatchedBridge *Bridge // 用于保存最后一个匹配的 Bridge
    found := false
    // 使用正则表达式检查是否符合[%s][%d]+[%d]格式，并去除所有方括号
    rePattern := `^\[(.*?)\]\[(\d+)\](\+|➕)\[(\d+)\]$`
    re := regexp.MustCompile(rePattern)
    matches := re.FindStringSubmatch(content)
    var contentWithoutBrackets string
    if len(matches) > 0 {
        // 如果匹配到，组合字符串并去除方括号
        contentWithoutBrackets = matches[1] + matches[2] + matches[3] + matches[4]
    } else {
        // 如果不符合[%s][%d]+[%d]格式，检查是否存在单独的方括号
        if strings.Count(content, "[") == strings.Count(content, "]") && strings.Count(content, "[") > 0 {
            // 如果文本包含成对的方括号，去除方括号
            contentWithoutBrackets = strings.Replace(content, "[", "", -1)
            contentWithoutBrackets = strings.Replace(contentWithoutBrackets, "]", "", -1)
        } else {
            // 如果不包含成对的方括号，使用原始文本
            contentWithoutBrackets = content
        }
    }
    
    for _, bridge := range allBridges {
        messages, err := getBridgeMessageHistory(bridge.ID)
        if err != nil {
            fmt.Printf("Error retrieving message history for bridge [%s]. Error: %v\n", bridge.ID, err)
            continue
        }
        for _, historyMsg := range messages {
            if strings.Contains(contentWithoutBrackets, historyMsg) {
                // 使用正则表达式匹配并提取支付金额
                re := regexp.MustCompile(`(\+|➕)(\d+)$`)
                matches := re.FindStringSubmatch(contentWithoutBrackets)
                if len(matches) > 1 { // 如果找到匹配的支付金额
                    payment, err = strconv.Atoi(matches[2])  // 将匹配的数字字符串转换为整型
                    if err != nil {
                        fmt.Printf("Error converting payment amount to integer: %v\n", err)
                        return
                    }
                }
    
                // 去除消息末尾的 "+数字"（支付金额）
                contentWithoutPayment := re.ReplaceAllString(contentWithoutBrackets, "")
                foundMatches++
                gameID = historyMsg
                remainingContent := strings.Replace(contentWithoutPayment, gameID, "", 1)
                starsToAdd, err = strconv.Atoi(remainingContent)
                if err != nil {
                    fmt.Printf("Error converting stars to integer: %v\n", err)
                    return
                }
                lastMatchedBridge = bridge // 保存最后一个匹配的 Bridge
                found = true
                break // 找到匹配项，中断内部循环
            }
        }
        if found {
            break // 找到匹配的 Bridge，中断外部循环
        }
    }

    if found && lastMatchedBridge != nil {
        // 根据最后一个匹配的 Bridge 创建副本
        bridgeCopy := Bridge{
            ID:                lastMatchedBridge.ID,
            GroupID:           lastMatchedBridge.GroupID,
            GroupName:         lastMatchedBridge.GroupName,
            GroupUserNickName: lastMatchedBridge.GroupUserNickName,
            WeChatUser:        lastMatchedBridge.WeChatUser,
            IsActive:          lastMatchedBridge.IsActive,
            IsCompleted:       lastMatchedBridge.IsCompleted,
            Msg:               lastMatchedBridge.Msg,
            GameID:            gameID,
            Stars:             lastMatchedBridge.Stars,
            StarCost:          lastMatchedBridge.StarCost,
            OrderType:         lastMatchedBridge.OrderType, 
            CreatedAt:         lastMatchedBridge.CreatedAt,
            LastMessageTime:   time.Now(),
            FinalRank:         lastMatchedBridge.FinalRank, 
        }
        
        foundBridge := &bridgeCopy 
        updateBridgeGameIDAndStars(foundBridge.ID, gameID, starsToAdd)
        // 检查是否有支付金额并构造相应的订单信息
        var formattedMessage string
        var existingPayment sql.NullInt64
        checkExpenditureSQL := `SELECT Payment FROM Expenditures WHERE BridgeID = ?`

        err := db.QueryRow(checkExpenditureSQL, foundBridge.ID).Scan(&existingPayment)
        if err != nil && err != sql.ErrNoRows {
            fmt.Printf("Error querying expenditure record: %v\n", err)
            return
        }
        username := foundBridge.GroupUserNickName
        if payment > 0 {
            formattedMessage = fmt.Sprintf("订单信息已记录：游戏ID [%s], 星数 [%d], 支付金额 [%d]。", gameID, starsToAdd, payment)
            fmt.Printf("桥梁信息已更新：游戏ID [%s], 星数 [%d], 支付金额 [%d]\n", gameID, starsToAdd, payment)
        
            if existingPayment.Valid {
                var updateExpenditureSQL string
                if foundBridge.GroupName == "代发" {
                    // 如果是代发，更新 OpenID
                    updateExpenditureSQL = `UPDATE Expenditures SET Payment = ?, OpenID = ? WHERE BridgeID = ?`
                    _, err := db.Exec(updateExpenditureSQL, payment, foundBridge.GroupID, foundBridge.ID)
                    if err != nil {
                        fmt.Printf("Error updating expenditure record: %v\n", err)
                        return
                    }
                } else {
                    // 如果不是代发，不更新 OpenID
                    updateExpenditureSQL = `UPDATE Expenditures SET Payment = ? WHERE BridgeID = ?`
                    _, err := db.Exec(updateExpenditureSQL, payment, foundBridge.ID)
                    if err != nil {
                        fmt.Printf("Error updating expenditure record: %v\n", err)
                        return
                    }
                }
            } else {
                var insertExpenditureSQL string
                if foundBridge.GroupName == "代发" {
                    // 如果是代发，插入 OpenID
                    insertExpenditureSQL = `INSERT INTO Expenditures (NickName, Payment, BridgeID, OpenID) VALUES (?, ?, ?, ?)`
                    fmt.Printf("Inserting into Expenditures with NickName: %s, Payment: %d, BridgeID: %s, OpenID: %s\n", senderNickName, payment, foundBridge.ID, foundBridge.GroupID)
                    _, err := db.Exec(insertExpenditureSQL, senderNickName, payment, foundBridge.ID, foundBridge.GroupID)
                    if err != nil {
                        fmt.Printf("Error inserting expenditure record: %v\n", err)
                        return
                    }
                } else {
                    // 如果不是代发，不插入 OpenID
                    insertExpenditureSQL = `INSERT INTO Expenditures (NickName, Payment, BridgeID) VALUES (?, ?, ?)`
                    _, err := db.Exec(insertExpenditureSQL, senderNickName, payment, foundBridge.ID)
                    if err != nil {
                        fmt.Printf("Error inserting expenditure record: %v\n", err)
                        return
                    }
                }
            }
        
            // 确定Creditor
            var creditor string = "国服车队联系员-梦乐" // 默认值
            
            // 如果是代发，则查询groupid对应的用户信息
            if foundBridge.GroupName == "代发" {
                // 首先通过groupid查询users表中的wechatname
                var wechatname string
                err := db.QueryRow(`
                    SELECT wechatname 
                    FROM users 
                    WHERE openid = ?`, 
                    foundBridge.GroupID).Scan(&wechatname)
                    
                if err == nil && wechatname != "" {
                    // 然后通过wechatname查询friends表中的nickName
                    var nickName string
                    err = db.QueryRow(`
                        SELECT nickName 
                        FROM friends 
                        WHERE userName = ?`, 
                        wechatname).Scan(&nickName)
                        
                    if err == nil && nickName != "" {
                        creditor = nickName // 使用找到的nickName作为creditor
                        fmt.Printf("使用代发人的昵称作为Creditor: %s\n", creditor)
                    } else {
                        fmt.Printf("未找到对应的friends记录或发生错误: %v, 使用默认Creditor\n", err)
                    }
                } else {
                    fmt.Printf("未找到对应的users记录或发生错误: %v, 使用默认Creditor\n", err)
                }
            }
        
            // 发送 HTTP 请求
            data := PaymentData{
                BridgeID:    foundBridge.ID,
                Payment:     payment,
                Debtor:      senderNickName,
                Creditor:    creditor,
            }
        
            jsonData, err := json.Marshal(data)
            if err != nil {
                fmt.Printf("Error marshaling data: %v\n", err)
                return
            }
        
            url := "http://www.moki-flanke.icu:8080/api/payment" // 替换为实际的 API 路由
            req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
            if err != nil {
                fmt.Printf("Error creating request: %v\n", err)
                return
            }
        
            req.Header.Set("Content-Type", "application/json")
        
            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                fmt.Printf("Error sending request: %v\n", err)
                return
            }
            defer resp.Body.Close()
        
            if resp.StatusCode != http.StatusOK {
                fmt.Printf("Error response from server: %v\n", resp.Status)
            }
        
            fmt.Println("请求已成功发送")
        
            if foundBridge.GroupName == "代发" {
                // 代发情况：发送订阅消息
                var openid string
                openid = foundBridge.GroupID
                accessToken, err := getMiniAccessToken()
                if err != nil {
                    fmt.Println("Error getting accessToken:", err)
                    return
                }
        
                // 构建订阅消息内容
                data3 := map[string]interface{}{
                    "thing1":   map[string]string{"value": senderNickName},
                    "amount10": map[string]string{"value": fmt.Sprintf("%d元", payment)},
                    "thing12":  map[string]string{"value": foundBridge.Msg},
                }
        
                // 构建订阅消息结构体
                subscribeMessage := map[string]interface{}{
                    "touser":           openid,
                    "template_id":      "oVsXdWABrZ3XwL95iFlsyKlrK0ynuXhp26_GR3PBDNg", // 替换为你的订阅消息模板 ID
                    "page":             "pages/order_list/order_list",
                    "miniprogram_state": "formal",
                    "lang":             "zh_CN",
                    "data":             data3,
                }
        
                // 发送订阅消息
                err = sendSubscribeMessage(accessToken, subscribeMessage)
                if err != nil {
                    fmt.Println("Error sending subscribe message:", err)
                    return
                }
        
                fmt.Println("Subscribe message sent successfully!")
            }
        } else {
            fmt.Printf("桥梁信息已更新：游戏ID [%s], 星数 [%d]\n", gameID, starsToAdd)
            var orderType string
            err = db.QueryRow("SELECT OrderType FROM Bridges WHERE ID = ?", foundBridge.ID).Scan(&orderType)
            if err != nil {
                fmt.Printf("Error querying final rank for bridge [%s]: %v\n", foundBridge.ID, err)
                return
            }
            initialRanks := []string{}
            ranksAndPrices, err := getRanksAndPrices(db)
            if err != nil {
                fmt.Printf("Error getting ranks and prices: %v\n", err)
                return
            }
        
            // 对ranksAndPrices按照段位长度进行排序
            var ranks []string
            for rank := range ranksAndPrices {
                ranks = append(ranks, rank)
            }
            sort.Slice(ranks, func(i, j int) bool {
                return len(ranks[i]) > len(ranks[j])
            })
            // 解析 bridge.Msg 来获取匹配的段位
            var matchedRanks []string
            input := foundBridge.Msg
            for _, rank := range ranks {
                rankOccurrences := strings.Count(input, rank)
                for i := 0; i < rankOccurrences; i++ {
                    matchedRanks = append(matchedRanks, rank)
                    input = strings.Replace(input, rank, "", 1)
                }
            }
            initialRanks = matchedRanks
            _, totalStarsNeeded, err := getTargetRankAndPriceSum(db, initialRanks, starsToAdd)
            if err != nil {
                fmt.Printf("Error calculating target rank and stars: %v\n", err)
                return
            }
        
            // 如果订单类型是"代练"，将星卷消耗除以2
            if orderType == "代练" {
                totalStarsNeeded = (totalStarsNeeded + 1) / 2
            }
            if existingPayment.Valid {
                // 执行更新操作
                updateExpenditureSQL := `UPDATE Expenditures SET Payment = ? WHERE BridgeID = ?`
                _, err = db.Exec(updateExpenditureSQL, totalStarsNeeded, foundBridge.ID)
                if err != nil {
                    fmt.Printf("Error updating expenditure record: %v\n", err)
                    return
                }
            } else {
                // 执行插入操作
                insertExpenditureSQL := `INSERT INTO Expenditures (NickName, Payment, BridgeID) VALUES (?, ?, ?)`
                _, err = db.Exec(insertExpenditureSQL, senderNickName, totalStarsNeeded, foundBridge.ID)
                if err != nil {
                    fmt.Printf("Error inserting expenditure record: %v\n", err)
                    return
                }
            }
            
            // 确定Creditor
            var creditor string = "国服车队联系员-梦乐" // 默认值
            
            // 如果是代发，则查询groupid对应的用户信息
            if foundBridge.GroupName == "代发" {
                // 首先通过groupid查询users表中的wechatname
                var wechatname string
                err := db.QueryRow(`
                    SELECT wechatname 
                    FROM users 
                    WHERE openid = ?`, 
                    foundBridge.GroupID).Scan(&wechatname)
                    
                if err == nil && wechatname != "" {
                    // 然后通过wechatname查询friends表中的nickName
                    var nickName string
                    err = db.QueryRow(`
                        SELECT nickName 
                        FROM friends 
                        WHERE userName = ?`, 
                        wechatname).Scan(&nickName)
                        
                    if err == nil && nickName != "" {
                        creditor = nickName // 使用找到的nickName作为creditor
                        fmt.Printf("使用代发人的昵称作为Creditor: %s\n", creditor)
                    } else {
                        fmt.Printf("未找到对应的friends记录或发生错误: %v, 使用默认Creditor\n", err)
                    }
                } else {
                    fmt.Printf("未找到对应的users记录或发生错误: %v, 使用默认Creditor\n", err)
                }
            }
            
            // 发送 HTTP 请求
            data := PaymentData{
                BridgeID:    foundBridge.ID,
                Payment:     totalStarsNeeded,
                Debtor:      senderNickName,
                Creditor:    creditor,
            }
        
            jsonData, err := json.Marshal(data)
            if err != nil {
                fmt.Printf("Error marshaling data: %v\n", err)
                return
            }
        
            url := "http://www.moki-flanke.icu:8080/api/payment" // 替换为实际的 API 路由
            req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
            if err != nil {
                fmt.Printf("Error creating request: %v\n", err)
                return
            }
        
            req.Header.Set("Content-Type", "application/json")
        
            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                fmt.Printf("Error sending request: %v\n", err)
                return
            }
            defer resp.Body.Close()
        
            if resp.StatusCode != http.StatusOK {
                fmt.Printf("Error response from server: %v\n", resp.Status)
            }
        
            fmt.Println("请求已成功发送")  
            formattedMessage = fmt.Sprintf("订单信息已记录：游戏ID [%s], 星数 [%d], 支付金额 [%d]。", gameID, starsToAdd, totalStarsNeeded)
        }   
        err = closeBridgeByID(foundBridge.ID)
        if err != nil {
            fmt.Printf("Error closing bridge: %v\n", err)
            return
        }
        sendTextMessage(formattedMessage, fromUserName)
        updateUserTotalStars1(senderNickName, starsToAdd, foundBridge, foundMatches)
        imageDir := "/root/wechat/image"
        imagePath := imageDir + senderNickName + "_收款码.jpg"

        // 检查图片文件是否存在
        if _, err := os.Stat(imagePath); err == nil {
            // 文件存在
            sendTextMessage("以下图片来自用户：" + senderNickName, "国1车队联系员-梦奇（24小时ai在）")

            if err := sendImage(imagePath, "国1车队联系员-梦奇（24小时ai在）"); err != nil {
                fmt.Printf("发送图片失败: %v\n", err)
            }
            // 处理未结账记录
            handleUnsettledRecords(senderNickName, db)
        } else if os.IsNotExist(err) {
            // 文件不存在
            sendTextMessage("#小程序://LT莱特电竞/yNCyj4shDsAEmXk，进入小程序自行提现", fromUserName)
        }
        // 处理完后，从映射中移除该用户
        delete(pendingImages, senderNickName)
        if foundBridge.GroupID == "网站" {
            var openid string
            err = db.QueryRow("SELECT openid FROM users WHERE username = ?", username).Scan(&openid)
            if err != nil {
                fmt.Println("Error fetching openid:", err)
                return
            }
            accessToken, err := getAccessToken()
            if err != nil {
                fmt.Println("Error getting access token:", err)
                return
            }
            // 发送第二个模板消息
            shortID := foundBridge.ID
            if len(foundBridge.ID) > 8 {
                shortID = foundBridge.ID[:8]
            }
            data2 := make(map[string]TemplateData)
            data2["character_string8"] = TemplateData{Value: shortID, Color: "#173177"} // 订单号，设置颜色为深蓝色
            data2["time23"] = TemplateData{Value: foundBridge.CreatedAt.Format("2006-01-02 15:04:05"), Color: "#173177"} // 开始时间，设置颜色为深蓝色
            if foundBridge.FinalRank.Valid {
                data2["thing11"] = TemplateData{Value: foundBridge.FinalRank.String, Color: "#FF0000"} // 下单用户，设置颜色为红色
            } else {
                data2["thing11"] = TemplateData{Value: "未知", Color: "#FF0000"} // 如果 FinalRank 无效，则设置为 "未知"
            }
            data2["amount4"] = TemplateData{Value: strconv.Itoa(foundBridge.StarCost), Color: "#008000"} // 订单金额，设置颜色为绿色
            // 构建第二个模板消息结构体
            templateMessage2 := TemplateMessage{
                Touser:     openid,
                TemplateID: "vLfQnKP6znx7KQApphaMVgTSHEg6k40TuyI2h77Lj4o", // 替换为你的第二个模板 ID
                URL:        "https://www.moki-flanke.icu",                 // 设置跳转链接
                Data:       data2,
            }
            // 发送第二个模板消息
            err = sendTemplateMessage(accessToken, templateMessage2)
            if err != nil {
                fmt.Println("Error sending second template message:", err)
                return
            }
            fmt.Println("Second template message sent successfully!")
        }
    }
}

func checkFormattingAndRespond(content string, fromUserName string, senderNickName string,) {
    content = strings.Replace(content, "[", "", -1)
    content = strings.Replace(content, "]", "", -1)
    // 检查是否包含"净胜"
    if strings.Contains(content, "净胜") {
        sendTextMessage(fmt.Sprintf("注意格式，请去掉'净胜'"), fromUserName)
        return // 如果发现格式问题则结束执行
    }

    // 检查是否包含货币符号或"金额"这个词，作为通用的表示金钱的方式
    if strings.Contains(content, "金额") {
        sendTextMessage(fmt.Sprintf("注意格式，请去掉金额"), fromUserName)
        return // 如果发现格式问题则结束执行
    }

    // 使用正则表达式从消息内容中提取数字
    re := regexp.MustCompile(`\d+`)
    numbers := re.FindAllString(content, -1)

    // 检查是否为单个8位纯数字（可能是绑定码）
    isBindCode := false
    if len(numbers) == 1 && len(numbers[0]) == 8 && numbers[0] == content {
        isBindCode = true
    }

    // 如果不是绑定码且不包含"+"，则进行金额检查
    if !isBindCode && !strings.Contains(content, "+") {
        for _, numStr := range numbers {
            num, err := strconv.Atoi(numStr)
            if err == nil && num > 40 {
                sendTextMessage(fmt.Sprintf("请检查您的输入是否有误，金额前面要加个"+""), fromUserName)
                return // 数字转换成功且大于40，给出提示后结束执行
            }
        }
    }
    // 如果没有格式问题，继续进行常规处理
    processNumericResponse(content, fromUserName, senderNickName)
}
func findAllBridgesForWeChatUser(weChatUserName string) ([]*Bridge, error) {
    rows, err := db.Query("SELECT * FROM Bridges WHERE WeChatUser = ?", weChatUserName)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var bridges []*Bridge
    for rows.Next() {
        var bridge Bridge
        if err := rows.Scan(
            &bridge.ID, &bridge.GroupID, &bridge.GroupName, &bridge.GroupUserNickName, 
            &bridge.WeChatUser, &bridge.IsActive, &bridge.IsCompleted, &bridge.Msg, 
            &bridge.GameID, &bridge.Stars, &bridge.StarCost, &bridge.OrderType,
            &bridge.CreatedAt, &bridge.LastMessageTime, &bridge.FinalRank, &bridge.WeChatUsername, // Add & before bridge.WeChatUsername
        ); err != nil {
            return nil, err
        }
        bridges = append(bridges, &bridge)
    }
    if err = rows.Err(); err != nil {
        return nil, err
    }
    return bridges, nil
}
func getBridgeMessageHistory(bridgeID string) ([]string, error) {
    var messages []string
    // 保持原有查询不变（按需可添加Role字段）
    rows, err := db.Query(`
        SELECT Message 
        FROM BridgeMessages 
        WHERE BridgeID = ? 
        ORDER BY Timestamp`, 
        bridgeID)
    if err != nil {
        return nil, fmt.Errorf("Error querying messages for bridge [%s]: %v", bridgeID, err)
    }
    defer rows.Close()

    for rows.Next() {
        var message string
        if err := rows.Scan(&message); err != nil {
            return nil, err
        }
        messages = append(messages, message)
    }

    if err = rows.Err(); err != nil {
        return nil, err
    }

    return messages, nil
}
// 更新桥梁的GameID和星数
func updateBridgeGameIDAndStars(bridgeID, gameID string, newStars int) {
    // 首先，更新桥梁的GameID和Stars
    _, err := db.Exec("UPDATE Bridges SET GameID = ?, Stars = ? WHERE ID = ?", gameID, newStars, bridgeID)
    if err != nil {
        fmt.Printf("Error updating bridge [%s] with new game ID [%s] and stars [%d]: %v\n", bridgeID, gameID, newStars, err)
        return
    }
    fmt.Printf("Successfully updated bridge [%s] with new game ID [%s] and stars [%d]\n", bridgeID, gameID, newStars)
}
func closeBridgeByID(bridgeID string) error {
    // 查询桥梁以获取 GroupUserNickName 和 GroupID
    var groupUserNickName, groupID, aiName string
    err := db.QueryRow("SELECT GroupUserNickName, GroupID FROM Bridges WHERE ID = ?", bridgeID).Scan(&groupUserNickName, &groupID)
    if err != nil {
        fmt.Printf("Error retrieving bridge info for bridge [%s]: %v\n", bridgeID, err)
        return err
    }

    // 关闭指定的桥梁
    _, err = db.Exec("UPDATE Bridges SET IsActive = 0 WHERE ID = ?", bridgeID)
    if err != nil {
        fmt.Printf("Error closing bridge [%s]: %v\n", bridgeID, err)
        return err
    }
    fmt.Printf("桥梁 [%s] 已关闭\n", bridgeID)

    // 如果找到了群昵称和群ID，则通知群内成员需要建立新的桥
    if groupUserNickName != "" && groupID != "" {
        err := db.QueryRow("SELECT event_text FROM current_event WHERE id = 8 AND event_title = 'AI名称'").Scan(&aiName)
        if err != nil {
            fmt.Printf("从数据库获取AI名称失败: %s\n", err)
            return err
        }
        groupMessage := fmt.Sprintf("@%s，乖乖！需要时重新滴，记得给我%s五星好评哟！", groupUserNickName, aiName)
        sendTextMessage(groupMessage, groupID)
    }

    return nil
}
func updateUserStatsOnBridgeAssociation(nickName, groupNickName string) {
    var count int
    var existingGroupNickNames sql.NullString

    // 查询用户当前的统计信息
    err := db.QueryRow("SELECT COUNT(*), GroupNickNames FROM user_stats WHERE NickName = ?", nickName).Scan(&count, &existingGroupNickNames)
    if err != nil {
        fmt.Printf("Error querying user stats for [%s]: %v\n", nickName, err)
        return
    }
    fmt.Printf("Found [%d] user stats record(s) for user [%s]\n", count, nickName)

    // 当用户存在时更新记录
    if count > 0 {
        var newGroupNickNames string
        shouldAdd := true

        if existingGroupNickNames.Valid {
            groupNickNamesArray := strings.Split(existingGroupNickNames.String, ",")
            for _, existingGroupNickName := range groupNickNamesArray {
                if existingGroupNickName == groupNickName {
                    shouldAdd = false
                    fmt.Printf("Group nickname [%s] already exists in user stats for [%s]\n", groupNickName, nickName)
                    break
                }
            }
        }

        if shouldAdd {
            if existingGroupNickNames.Valid && existingGroupNickNames.String != "" {
                newGroupNickNames = existingGroupNickNames.String + ","
            }
            newGroupNickNames += groupNickName
            fmt.Printf("Adding new group nickname [%s] to user stats for [%s]\n", groupNickName, nickName)
        } else {
            newGroupNickNames = existingGroupNickNames.String
        }

        _, err = db.Exec("UPDATE user_stats SET BridgeCount = BridgeCount + 1, GroupNickNames = ? WHERE NickName = ?", newGroupNickNames, nickName)
        if err != nil {
            fmt.Printf("Error updating user stats for [%s]: %v\n", nickName, err)
        } else {
            fmt.Printf("User stats updated for [%s]. New group nicknames: %s\n", nickName, newGroupNickNames)
        }
    } else {
        // 当用户不存在时插入新记录
        _, err = db.Exec("INSERT INTO user_stats (NickName, GroupNickNames, TotalStars, BridgeCount, CompleteOrderCount) VALUES (?, ?, 0, 1, 0)", nickName, groupNickName)
        if err != nil {
            fmt.Printf("Error inserting new user stats for [%s]: %v\n", nickName, err)
        } else {
            fmt.Printf("New user stats record inserted for [%s]\n", nickName)
        }
    }
}

func sendPostRequest(transferID, userName string, port int) error {
	// 构造 POST 请求数据
	requestBody := Transfer{
		API:  2219,
		Data: struct {
			TransferID string `json:"transferid"`
			UserName   string `json:"userName"`
		}{
			TransferID: transferID,
			UserName:   userName,
		},
	}

	// 将数据转换为 JSON
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		return fmt.Errorf("序列化请求数据失败: %w", err)
	}

	// 构建请求 URL
	url := fmt.Sprintf("http://8.138.151.175:%d", port)

	// 发送 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("发送 POST 请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("POST 请求返回错误状态: %d", resp.StatusCode)
	}

	// 打印成功信息
	fmt.Printf("POST 请求成功，向服务器发送数据完成\n")
	return nil
}
func calculateMaxUpgradesAndRank(db *sql.DB, initialRanks []string, totalStars int) ([]string, int, error) {
    ranksCosts, err := getAllRanksAndCosts(db)
    if err != nil {
        return nil, 0, err
    }

    // 计算所有初始段位至少可以升级一次所需的最小星卷数
    minStarsNeededPerRank := make([]int, len(initialRanks))
    for i, initialRank := range initialRanks {
        found := false
        for _, rankCost := range ranksCosts {
            if rankCost[0] == initialRank {
                if nextIndex := findNextIndex(ranksCosts, initialRank, 1); nextIndex != -1 {
                    starCost, _ := strconv.Atoi(ranksCosts[nextIndex][1]) // 使用下一个段位的星卷消耗
                    minStarsNeededPerRank[i] = starCost
                } else {
                    starCost, _ := strconv.Atoi(rankCost[1]) // 没有更高段位时使用当前段位消耗
                    minStarsNeededPerRank[i] = starCost
                }
                found = true
                break
            }
        }
        if !found {
            return nil, 0, fmt.Errorf("初始段位 %s 未找到", initialRank)
        }
    }

    // 计算可进行的最大共同升级次数
    upgrades := 0
    for {
        currentUpgradeCost := 0
        for _, cost := range minStarsNeededPerRank {
            currentUpgradeCost += cost
        }

        if totalStars < currentUpgradeCost {
            break
        }

        totalStars -= currentUpgradeCost
        upgrades++

        // 更新下一轮所需的星卷数
        for i, rank := range initialRanks {
            nextIndex := findNextIndex(ranksCosts, rank, 1)
            if nextIndex != -1 && nextIndex+1 < len(ranksCosts) {
                initialRanks[i] = ranksCosts[nextIndex][0]
                starCost, _ := strconv.Atoi(ranksCosts[nextIndex][1]) // 使用再下一个段位的星卷消耗
                minStarsNeededPerRank[i] = starCost
            }
        }
    }

    finalRanks := make([]string, len(initialRanks))
    copy(finalRanks, initialRanks) // After all possible upgrades, copy the final ranks

    return finalRanks, upgrades, nil
}
// 兑换充值码
func redeemRechargeCode(db *sql.DB, code string) (float64, error) {
    var amount float64
    var used int

    // 查询充值码对应的金额和使用状态
    err := db.QueryRow("SELECT amount, used FROM recharge_records WHERE recharge_code = ?", code).Scan(&amount, &used)
    if err != nil {
        if err == sql.ErrNoRows {
            return 0, fmt.Errorf("充值码不存在")
        }
        return 0, fmt.Errorf("查询充值码出错: %s", err)
    }

    if used != 0 {
        return 0, fmt.Errorf("充值码已被使用")
    }

    // 将充值码标记为已使用
    _, err = db.Exec("UPDATE recharge_records SET used = 1 WHERE recharge_code = ?", code)
    if err != nil {
        return 0, fmt.Errorf("更新充值码状态失败: %s", err)
    }

    return amount, nil
}
func handleNullInt64(i sql.NullInt64) int64 {
    if i.Valid {
        return i.Int64
    }
    return 0
}
func updateStarsCount(db *sql.DB, groupName string, senderNickName string, amount float64) (int, error) {
    // 将金额转换为星卷，这里假设1星卷等于5元
    var discount int
    err := db.QueryRow("SELECT Discount FROM UserDiscounts WHERE NickName = ?", senderNickName).Scan(&discount)
    if err != nil {
        if err == sql.ErrNoRows {
            log.Printf("未找到用户折扣记录, 使用默认折扣: 昵称=%s", senderNickName)
            discount = 100 // 默认折扣为100%
        } else {
            log.Printf("查询折扣记录失败: 昵称=%s, 错误=%s", senderNickName, err)
            return 0, err
        }
    } else {
        log.Printf("查询折扣记录成功: 昵称=%s, 折扣=%d%%", senderNickName, discount)
    }

    // 折扣后的实际金额计算
    effectiveAmount := amount * (100.0 / float64(discount))

    // 计算得到的星卷数量
    stars := int(effectiveAmount / 5)
    log.Printf("折扣后金额计算完成: 折扣后金额=%.2f, 计算得星卷数=%d", effectiveAmount, stars)

    // 检查用户在指定群组中是否已有星卷记录
    var existingStars int
    err = db.QueryRow("SELECT StarsCount FROM member_stars WHERE GroupID = ? AND UserName = ?", groupName, senderNickName).Scan(&existingStars)
    
    if err != nil && err != sql.ErrNoRows {
        log.Printf("查询星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", groupName, senderNickName, err)
        return 0, err
    }

    if err == sql.ErrNoRows {
        // 插入新记录
        _, err = db.Exec("INSERT INTO member_stars (GroupID, UserName, StarsCount) VALUES (?, ?, ?)", groupName, senderNickName, stars)
        if err != nil {
            log.Printf("插入新的星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", groupName, senderNickName, err)
            return 0, err
        }
        log.Printf("插入新的星卷记录成功: 群组=%s, 昵称=%s, 星卷数=%d", groupName, senderNickName, stars)
    } else {
        // 更新现有记录
        _, err = db.Exec("UPDATE member_stars SET StarsCount = StarsCount + ? WHERE GroupID = ? AND UserName = ?", stars, groupName, senderNickName)
        if err != nil {
            log.Printf("更新星卷记录失败: 群组=%s, 昵称=%s, 错误=%s", groupName, senderNickName, err)
            return 0, err
        }
        log.Printf("更新星卷记录成功: 群组=%s, 昵称=%s, 新增星卷数=%d", groupName, senderNickName, stars)
    }

    return stars, nil
}
func findNextIndex(ranksCosts [][2]string, currentRank string, steps int) int {
    currentIndex := -1
    for i, rankCost := range ranksCosts {
        if rankCost[0] == currentRank {
            currentIndex = i
            break
        }
    }

    if currentIndex == -1 || currentIndex+steps >= len(ranksCosts) {
        return -1
    }

    return currentIndex + steps
}
func generateContent(db *sql.DB, orders []string, orderType string, starsCount int, Mu []string) (string, error) {
    // 去掉 "来个" 两个字符
    if strings.HasPrefix(orderType, "来个") {
        orderType = strings.TrimPrefix(orderType, "来个")
    }

    var matchedRanks []string
    var totalPrice int
    ranksAndPrices, err := getRanksAndPrices(db)  // 假设这个函数返回段位和价格的映射
    if err != nil {
        fmt.Printf("Error getting ranks and prices: %v\n", err)
        return "", err
    }

    // 对ranksAndPrices按照段位长度进行排序
    var ranks []string
    for rank := range ranksAndPrices {
        ranks = append(ranks, rank)
    }
    sort.Slice(ranks, func(i, j int) bool {
        return len(ranks[i]) > len(ranks[j])
    })

    var remainingOrders []string
    var initialRankOrder, targetRankOrder int

    for _, input := range orders {
        for _, rank := range ranks {
            rankOccurrences := strings.Count(input, rank) // 计算段位在输入中出现的次数
            for i := 0; i < rankOccurrences; i++ {
                matchedRanks = append(matchedRanks, rank)
                totalPrice += ranksAndPrices[rank]
                input = strings.Replace(input, rank, "", 1) // 移除第一个匹配的段位
            }
        }
        remainingOrders = append(remainingOrders, strings.TrimSpace(input)) // 保留处理后的输入文本
    }
    err = db.QueryRow("SELECT RankOrder FROM RankPrices WHERE Rank = ?", matchedRanks[0]).Scan(&initialRankOrder)
    if err != nil {
        fmt.Printf("Error getting initial rank order: %v\n", err)
        return "", err
    }
    // 查询目标段位的 RankOrder
    err = db.QueryRow("SELECT RankOrder FROM RankPrices WHERE Rank = ?", Mu[0]).Scan(&targetRankOrder)
    if err != nil {
        fmt.Printf("Error getting target rank order: %v\n", err)
        return "", err
    }
    maxUpgrades := targetRankOrder - initialRankOrder

    for i := range remainingOrders {
        remainingOrders[i] = strings.ReplaceAll(remainingOrders[i], ",", "")
        remainingOrders[i] = strings.ReplaceAll(remainingOrders[i], " ", "")
    }
    content := strings.Join(remainingOrders, "") // 使用剩余的订单文本
    switch orderType {
    case "车队":
        if (len(matchedRanks) > 1) {
            totalPrice -= 1
        }
        content = strings.Join(remainingOrders, " ") // 使用剩余的订单文本
        if len(matchedRanks) > 0 {
            content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + strconv.Itoa(totalPrice)
        } else {
            content += "，群价"
        }
        content += ",最多打" + strconv.Itoa(maxUpgrades) + "净胜"
        content += "，复制信息发我，#秒开车队来"

        if isInternalOrderMode {
            forwardMessageToAllGroupsneibu(db, content)
        } else {
            forwardMessageToAllGroupswaibu(db, content)
        }
    case "陪玩":
        content = strings.Join(orders, " ") + " 群价" + "，复制信息发我，#技术娱乐陪接" // 使用原始订单文本
        if isInternalOrderMode {
            forwardMessageToAllGroupsneibu(db, content)
        } else {
            forwardMessageToAllGroupspeiwan(db, content)
        }
    case "小姐姐":
        content = strings.Join(orders, " ") + " 群价" + "，复制信息发我，#小姐姐接" // 使用原始订单文本
        if isInternalOrderMode {
            forwardMessageToAllGroupsneibu(db, content)
        } else {
            forwardMessageToAllGroupsxjj(db, content)
        }
    case "代练":
        if len(matchedRanks) > 1 {
            totalPrice -= 1
        }
        content = strings.Join(remainingOrders, " ")
        if len(matchedRanks) > 0 {
            adjustedPrice := float64(totalPrice) / 2.0 // 将 totalPrice 转为浮点数进行除法运算
            formattedPrice := fmt.Sprintf("%.1f", adjustedPrice) // 将浮点数格式化为字符串，保留一位小数
            content += "，" + strings.Join(matchedRanks, "+") + "，单价：" + formattedPrice
        } else {
            content += "，群价"
        }
        content += ",最多打" + strconv.Itoa(maxUpgrades) + "♥"
        content += "，复制信息发我，#通天代接"

        if isInternalOrderMode {
            forwardMessageToAllGroupsneibu(db, content)
        } else {
            forwardMessageToAllGroupsdailian(db, content)
        }
    }

    return content, nil
}
func getOpenIDFromCode(code string) (string, error) {
    // 小程序的 appid 和 appSecret
    appID := "wx86cbc2487aeab9fd"       // 替换为你的小程序 appid
    appSecret := "70cf597a7a577253071407db03f7ba6f"  // 替换为你的小程序 appSecret

    // 构建请求 URL，调用小程序的 jscode2session 接口
    url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appID, appSecret, code)

    // 发送请求获取 openid 和 session_key
    resp, err := http.Get(url)
    if err != nil {
        return "", fmt.Errorf("请求微信接口失败: %v", err)
    }
    defer resp.Body.Close()

    // 解析响应
    var result struct {
        OpenID    string `json:"openid"`
        SessionKey string `json:"session_key"`
        ErrCode   int    `json:"errcode"`
        ErrMsg    string `json:"errmsg"`
    }

    // 解码响应体
    err = json.NewDecoder(resp.Body).Decode(&result)
    if err != nil {
        return "", fmt.Errorf("解析微信接口响应失败: %v", err)
    }

    // 检查是否返回错误
    if result.ErrCode != 0 {
        return "", fmt.Errorf("获取 openid 失败: %s", result.ErrMsg)
    }

    // 返回 openid
    return result.OpenID, nil
}

func InitWeChatPayClient() (*core.Client, error) {
	mchID := "1698159272"
	mchCertificateSerialNumber := "52a8abc2de9ec43332d98f2969be0637972edf46"
	apiV3Key := "MIIEKDCCAxCgAwIBAgIUUqirwt6exDMy"
    privateKeyPath := "./apiclient_key.pem"

	privateKey, err := utils.LoadPrivateKeyWithPath(privateKeyPath)
	if err != nil {
		return nil, fmt.Errorf("加载商户私钥失败: %v", err)
	}

	client, err := core.NewClient(context.Background(),
		option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, privateKey, apiV3Key),
	)
	if err != nil {
		return nil, fmt.Errorf("初始化微信支付客户端失败: %v", err)
	}
	return client, nil
}
func GetRandomString(n int) string {
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	bytes := make([]byte, n)
	if _, err := rand.Read(bytes); err != nil {
		log.Printf("[ERROR] 随机字符串生成失败: %v", err)
		return ""
	}
	for i, b := range bytes {
		bytes[i] = letters[b%byte(len(letters))]
	}
	return string(bytes)
}
func SignWithSHA256RSA(data string, privateKey *rsa.PrivateKey) (string, error) {
	// 创建 SHA256 哈希
	hash := sha256.New()
	_, err := hash.Write([]byte(data))
	if err != nil {
		return "", fmt.Errorf("生成哈希失败: %v", err)
	}
	hashed := hash.Sum(nil)

	// 使用商户私钥对哈希值进行签名
	signature, err := rsa.SignPKCS1v15(cryptorand.Reader, privateKey, crypto.SHA256, hashed)
	if err != nil {
		return "", fmt.Errorf("签名失败: %v", err)
	}

	// 使用 Base64 编码签名
	return base64.StdEncoding.EncodeToString(signature), nil
}
func generateRandomString(n int) string {
    const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    rand.Seed(time.Now().UnixNano())
    b := make([]byte, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
    }
    return string(b)
}

// 生成唯一的邀请码
func generateUniqueInviteCode() string {
    rand.Seed(time.Now().UnixNano())
    for {
        inviteCode := strconv.Itoa(rand.Intn(900000) + 100000) // 生成6位数随机数
        var exists int
        err := db.QueryRow("SELECT COUNT(*) FROM users WHERE invite_code = ?", inviteCode).Scan(&exists)
        if err != nil {
            log.Printf("Error checking invite code existence: %v", err)
        }
        if exists == 0 {
            return inviteCode
        }
    }
}
func authMiddleware(db *sql.DB) gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)
        userIP := session.Get("userIP")
        currentIP := c.ClientIP()
        username := session.Get("user")

        if username != nil && userIP == currentIP {
            // 检查数据库中是否还存在该用户
            var exists bool
            err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)", username).Scan(&exists)
            if err != nil {
                // 数据库查询出错
                c.Redirect(http.StatusSeeOther, "/login")
                c.Abort()
                return
            }
            if exists {
                // 用户存在
                c.Next()
            } else {
                // 用户不存在
                session.Delete("user") // 清除会话中的用户信息
                session.Save()
                c.Redirect(http.StatusSeeOther, "/login")
                c.Abort()
            }
        } else {
            // 用户未登录或IP地址不匹配
            c.Redirect(http.StatusSeeOther, "/login")
            c.Abort()  // 防止继续处理当前请求
        }
    }
}
func getTotalFrozenStarCost(db *sql.DB, orderID string) (int, error) {
    query := `SELECT IFNULL(SUM(StarCost), 0) FROM StarFreeze WHERE ID = ?`
    var totalFrozenStarCost int
    err := db.QueryRow(query, orderID).Scan(&totalFrozenStarCost)
    if err != nil {
        return 0, err
    }
    return totalFrozenStarCost, nil
}
// 处理 NULL 值的帮助函数
func handleNullString(nullStr sql.NullString) string {
    if nullStr.Valid {
        return nullStr.String
    }
    return ""
}
func handleNullInt(nullInt sql.NullInt64) int {
    if nullInt.Valid {
        return int(nullInt.Int64)
    }
    return 0
}
func validateRank(db *sql.DB, orderType string, targetRanks, initialRanks []string, starsCount int) (bool, int, error) {
    totalFreezeStars := 0
    var upgradeCount int

    // 计算第一个段位的升星数
    if len(targetRanks) > 0 && targetRanks[0] != "" {
        initialRank := initialRanks[0]
        targetRank := targetRanks[0]
        fmt.Printf("Validating rank for order 1, initial rank: %s\n", initialRank)

        ranksCosts, err := getAllRanksAndCosts(db)
        if err != nil {
            return false, 0, fmt.Errorf("获取所有段位和花费失败: %v", err)
        }

        sort.Slice(ranksCosts, func(i, j int) bool {
            return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
        })

        for _, rankCost := range ranksCosts {
            if strings.Contains(initialRank, rankCost[0]) {
                initialRank = rankCost[0]
                break
            }
        }
        fmt.Printf("Mapped initial rank to base rank: %s\n", initialRank)

        startIndex, err := getAdjustedRankOrder(initialRank, db)
        if err != nil {
            return false, 0, fmt.Errorf("获取初始段位排序失败: %v", err)
        }

        targetIndex, err := getAdjustedRankOrder(targetRank, db)
        if err != nil {
            return false, 0, fmt.Errorf("获取目标段位排序失败: %v", err)
        }

        upgradeCount = targetIndex - startIndex
        fmt.Printf("Calculated upgrade count for order 1: %d\n", upgradeCount)
    } else {
        return false, 0, fmt.Errorf("第一个段位的目标段位不能为空")
    }

    // 根据第一个段位的升星数计算所有段位的星卷消耗
    for i := 0; i < len(initialRanks); i++ {
        initialRank := initialRanks[i]
        fmt.Printf("Validating rank for order %d, initial rank: %s\n", i+1, initialRank)

        ranksCosts, err := getAllRanksAndCosts(db)
        if err != nil {
            return false, 0, fmt.Errorf("获取所有段位和花费失败: %v", err)
        }

        sort.Slice(ranksCosts, func(i, j int) bool {
            return len(ranksCosts[i][0]) > len(ranksCosts[j][0])
        })

        for _, rankCost := range ranksCosts {
            if strings.Contains(initialRank, rankCost[0]) {
                initialRank = rankCost[0]
                break
            }
        }
        fmt.Printf("Mapped initial rank to base rank: %s\n", initialRank)

        // 获取需要的星卷总数
        _, totalStarsNeeded, err := getTargetRankAndStars(db, []string{initialRank}, upgradeCount)
        if err != nil {
            return false, 0, fmt.Errorf("获取需要的星卷总数失败: %v", err)
        }
        fmt.Printf("Total stars needed for order %d: %d\n", i+1, totalStarsNeeded)

        // 如果订单类型是"代练"，将星卷消耗除以2
        if orderType == "代练" {
            totalStarsNeeded = (totalStarsNeeded + 1) / 2
        }
        fmt.Printf("Adjusted total stars needed for order %d: %d\n", i+1, totalStarsNeeded)

        // 累积总的冻结星卷
        totalFreezeStars += totalStarsNeeded
    }

    if orderType == "小姐姐" || orderType == "陪玩" {
        totalFreezeStars = 0
    }
    fmt.Printf("Total freeze stars needed: %d\n", totalFreezeStars)

    // 判断当前星卷是否足够
    canProceed := starsCount >= totalFreezeStars
    fmt.Printf("Can proceed with order: %v\n", canProceed)

    return canProceed, totalFreezeStars, nil
}
// 生成新内容的函数
func generateNewContent(oldMsg string, newRanks []string, stars []string, orderType string) string {
    var maxUpgrades int
    var upgradeSymbol string
    contactInfo := ""
    reContact := regexp.MustCompile(`(微信|扣扣|q|Q|v|V)`)
    matchContact := reContact.FindStringSubmatch(oldMsg)
    if len(matchContact) > 1 {
        contactInfo = matchContact[1]
    }

    // 提取位置信息 - 修改为提取多个位置
    var positionInfos []string
    rePosition := regexp.MustCompile(`(野|边|中|射|辅)`)
    allPositions := rePosition.FindAllString(oldMsg, -1)

    // 如果提取到了位置信息，使用所有位置
    if len(allPositions) > 0 {
        positionInfos = allPositions
    }

    switch orderType {
    case "车队":
        upgradeSymbol = "净胜"
        maxUpgrades = extractMaxUpgrades(oldMsg, "最多打(\\d+)净胜")
    case "代练":
        upgradeSymbol = "♥"
        maxUpgrades = extractMaxUpgrades(oldMsg, "最多打(\\d+)♥")
    }
    minStars := math.MaxInt32
	for _, star := range stars {
		starCount, err := strconv.Atoi(star)
		if err != nil {
			continue
		}
		if starCount < minStars {
			minStars = starCount
		}
	}
    maxUpgrades -= minStars
    // 生成新的订单内容
    var newContent strings.Builder
    newContent.WriteString(contactInfo)
    // 添加位置信息 - 如果有多个位置，全部添加
    if len(positionInfos) > 0 {
        newContent.WriteString(strings.Join(positionInfos, ""))
        newContent.WriteString(" ")
    }
    newContent.WriteString(strings.Join(newRanks, "+"))
    switch orderType {
    case "车队":
        newContent.WriteString(fmt.Sprintf("，最多打%d%s", maxUpgrades, upgradeSymbol))
        newContent.WriteString("，复制信息发我，#")
        newContent.WriteString("秒开车队来")
    case "陪玩":
        newContent.WriteString("，复制信息发我，#")
        newContent.WriteString("技术娱乐陪接")
    case "小姐姐":
        newContent.WriteString("，复制信息发我，#")
        newContent.WriteString("小姐姐接")
    case "代练":
        newContent.WriteString(fmt.Sprintf("，最多打%d%s", maxUpgrades, upgradeSymbol))
        newContent.WriteString("，复制信息发我，#")
        newContent.WriteString("通天代接")
    }
    return newContent.String()
}
// 提取 maxUpgrades 的函数
func extractMaxUpgrades(msg, pattern string) int {
    re := regexp.MustCompile(pattern)
    matches := re.FindStringSubmatch(msg)
    if len(matches) > 1 {
        maxUpgrades, _ := strconv.Atoi(matches[1])
        return maxUpgrades
    }
    return 0
}
func handleRecords(db *sql.DB, settled bool) (map[string]BridgeInfo, error) {
    isSettled := 0
    if settled {
        isSettled = 1
    }

    query := `
    SELECT u.ID, u.WeChatUser, u.GameID, u.Stars, u.Msg, COALESCE(SUM(e.Payment), 0) AS Payment
    FROM UnsettledBridges u
    LEFT JOIN Expenditures e ON u.ID = e.BridgeID
    WHERE u.IsSettled = ?
    GROUP BY u.ID, u.GameID, u.Stars, u.Msg
    ORDER BY u.SettlementTime DESC`

    rows, err := db.Query(query, isSettled)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    bridgeInfos := make(map[string]BridgeInfo)
    bridgeStars := make(map[string][]int)

    for rows.Next() {
        var weChatUser, gameID, msg, bridgeID string
        var stars, payment int
        if err := rows.Scan(&bridgeID, &weChatUser, &gameID, &stars, &msg, &payment); err != nil {
            continue
        }

        bridgeStars[bridgeID] = append(bridgeStars[bridgeID], stars)

        if _, exists := bridgeInfos[bridgeID]; !exists {
            info := fmt.Sprintf("用户：%s,<br>订单信息：%s,<br>游戏ID：%s,<br>支付金额：%d<br>", weChatUser, msg, gameID, payment)
            bridgeInfos[bridgeID] = BridgeInfo{
                ID:           bridgeID,
                WeChatUser:   sanitizeFileName(weChatUser), 
                Info:         template.HTML(info), // Directly use template.HTML here
                TotalPayment: payment,
            }
        }
    }

    for bridgeID, bi := range bridgeInfos {
        starsText := strings.Join(strings.Fields(fmt.Sprint(bridgeStars[bridgeID])), "+")
        bi.Info = template.HTML(fmt.Sprintf("%s星数：%s<br>", bi.Info, starsText)) // Append stars info to the existing Info
        bridgeInfos[bridgeID] = bi
    }

    return bridgeInfos, nil
}

func getMediaIndexes() ([]int, error) {
    var indexes []int
    pattern := regexp.MustCompile(`^(\d+)\.jpg$`) // 正则表达式仅匹配.jpg文件

    // 处理图片文件夹
    err := filepath.Walk("./image", func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() && pattern.MatchString(info.Name()) {
            matches := pattern.FindStringSubmatch(info.Name())
            if len(matches) > 1 {
                id, err := strconv.Atoi(matches[1]) // matches[1] 是文件名的数字部分
                if err == nil {
                    indexes = append(indexes, id)
                }
            }
        }
        return nil
    })

    if err != nil {
        return nil, fmt.Errorf("error walking through image directory: %v", err)
    }

    return indexes, nil
}
func saveTaskToFile(task Task) {
    folderPath := fmt.Sprintf("./tasks/%s", task.ID)
    os.MkdirAll(folderPath, os.ModePerm)
    filePath := fmt.Sprintf("%s/task.json", folderPath)
    file, err := os.Create(filePath)
    if err != nil {
        fmt.Printf("创建文件失败: %v\n", err)
        return
    }
    defer file.Close()
    json.NewEncoder(file).Encode(task)
}
// UpdatePaymentStatus 直接操作数据库的函数
func UpdatePaymentStatus(bridgeID string) (int64, error) {
    // 执行数据库更新
    result, err := db2.Exec("UPDATE payments SET is_check = 1 WHERE bridge_id = ?", bridgeID)
    if err != nil {
        log.Printf("数据库更新失败: %v", err)
        return 0, err
    }

    rowsAffected, err := result.RowsAffected()
    if err != nil {
        log.Printf("获取影响行数失败: %v", err)
        return 0, err
    }

    if rowsAffected == 0 {
        log.Printf("警告: bridge_id=%s 未找到或数据未变更", bridgeID)
    }

    return rowsAffected, nil
}
// 生成8位随机数字绑定码
func generateBindCode() string {
    // 创建一个随机数生成器
    rand.Seed(time.Now().UnixNano())
    
    // 生成8位随机数字
    code := make([]byte, 8)
    for i := 0; i < 8; i++ {
        code[i] = byte('0' + rand.Intn(10))
    }
    
    return string(code)
}

// 保存绑定码到数据库
func saveBindCode(openID, bindCode string) error {
    // 检查是否已存在绑定记录
    var count int
    err := db.QueryRow("SELECT COUNT(*) FROM BindCodes WHERE openid = ?", openID).Scan(&count)
    if err != nil {
        return fmt.Errorf("检查绑定记录失败: %v", err)
    }
    
    // 处理事务
    tx, err := db.Begin()
    if err != nil {
        return fmt.Errorf("开始事务失败: %v", err)
    }
    
    if count > 0 {
        // 更新现有记录
        _, err = tx.Exec("UPDATE BindCodes SET code = ?, used = 0, created_at = CURRENT_TIMESTAMP WHERE openid = ?",
            bindCode, openID)
    } else {
        // 插入新记录
        _, err = tx.Exec("INSERT INTO BindCodes (openid, code, used, created_at) VALUES (?, ?, 0, CURRENT_TIMESTAMP)",
            openID, bindCode)
    }
    
    if err != nil {
        tx.Rollback()
        return fmt.Errorf("保存绑定码失败: %v", err)
    }
    
    return tx.Commit()
}

// 检查绑定码状态
func checkBindCode(code string) (string, bool, error) {
    var openID string
    var used int
    var createdAt time.Time
    
    err := db.QueryRow("SELECT openid, used, created_at FROM BindCodes WHERE code = ?", code).Scan(&openID, &used, &createdAt)
    if err != nil {
        if err == sql.ErrNoRows {
            return "", false, fmt.Errorf("绑定码不存在")
        }
        return "", false, fmt.Errorf("查询绑定码失败: %v", err)
    }
    
    // 检查绑定码是否过期（24小时有效期）
    if time.Since(createdAt) > 24*time.Hour {
        return "", false, fmt.Errorf("绑定码已过期")
    }
    
    return openID, used == 1, nil
}

// 标记绑定码为已使用并更新用户表
func markBindCodeAsUsed(code string, userName string, nickName string) error {
    tx, err := db.Begin()
    if err != nil {
        return fmt.Errorf("开始事务失败: %v", err)
    }
    
    // 获取openID
    var openID string
    err = tx.QueryRow("SELECT openid FROM BindCodes WHERE code = ?", code).Scan(&openID)
    if err != nil {
        tx.Rollback()
        return fmt.Errorf("获取openID失败: %v", err)
    }
    
    // 更新绑定码状态为已使用
    _, err = tx.Exec("UPDATE BindCodes SET used = 1 WHERE code = ?", code)
    if err != nil {
        tx.Rollback()
        return fmt.Errorf("更新绑定码状态失败: %v", err)
    }
    
    // 检查users表中是否已有该openID
    var id int
    err = tx.QueryRow("SELECT id FROM users WHERE openid = ?", openID).Scan(&id)
    if err != nil && err != sql.ErrNoRows {
        tx.Rollback()
        return fmt.Errorf("检查用户存在失败: %v", err)
    }
    
    if err == sql.ErrNoRows {
        // 该openID在users表中不存在，做插入操作
        // 此处仅是示例，实际情况可能需要更复杂的逻辑
        _, err = tx.Exec("INSERT INTO users (openid, wechatname, username, password) VALUES (?, ?, ?, ?)",
            openID, userName, "wx_"+openID[:8], "defaultpassword")
        if err != nil {
            tx.Rollback()
            return fmt.Errorf("创建用户失败: %v", err)
        }
    } else {
        // 该openID在users表中存在，更新wechatname
        _, err = tx.Exec("UPDATE users SET wechatname = ? WHERE openid = ?", userName, openID)
        if err != nil {
            tx.Rollback()
            return fmt.Errorf("更新用户失败: %v", err)
        }
    }
    
    return tx.Commit()
}
// 微信退款函数
func initiateWechatRefund(transactionId, outTradeNo string, amount float64, reason string) {
    log.Printf("[INFO] 开始处理微信退款: 交易号=%s, 金额=%.2f, 原因=%s", transactionId, amount, reason)
    
    // 初始化微信支付客户端
    client, err := InitWeChatPayClient()
    if err != nil {
        log.Printf("[ERROR] 初始化微信支付客户端失败: %v", err)
        return
    }
    
    // 生成唯一退款单号
    refundNo := fmt.Sprintf("R%s%d", time.Now().Format("20060102"), time.Now().UnixNano()%1000000)
    if len(refundNo) > 32 {
        refundNo = refundNo[:32]
    }
    
    // 创建 RefundsApiService 服务实例
    svc := refunddomestic.RefundsApiService{Client: client}

    // 构建退款请求
    amountInfo := &refunddomestic.AmountReq{
        Refund:   core.Int64(int64(amount * 100)), // 转换为分
        Total:    core.Int64(int64(amount * 100)), // 原订单金额，转换为分
        Currency: core.String("CNY"),
    }
    
    req := refunddomestic.CreateRequest{}
    
    // 设置交易ID或商户订单号(二选一)
    if transactionId != "" {
        req.TransactionId = core.String(transactionId)
    } else if outTradeNo != "" {
        req.OutTradeNo = core.String(outTradeNo)
    } else {
        log.Printf("[ERROR] 退款请求缺少交易ID和商户订单号")
        return
    }
    
    // 设置其他必要参数
    req.OutRefundNo = core.String(refundNo)
    req.Reason = core.String(reason)
    req.NotifyUrl = core.String("https://www.moki-flanke.icu/api/guarantee/refundNotify")
    req.Amount = amountInfo

    // 发送退款请求
    resp, result, err := svc.Create(context.Background(), req)
    
    if err != nil {
        log.Printf("[ERROR] 发起微信退款失败: %v", err)
        // 记录失败的退款请求，以便后续重试
        _, dbErr := db.Exec(
            `INSERT INTO RefundFailures 
            (TransactionID, OutTradeNo, Amount, Reason, ErrorMessage, CreateTime) 
            VALUES (?, ?, ?, ?, ?, ?)`,
            transactionId,
            outTradeNo,
            amount,
            reason,
            err.Error(),
            time.Now().Format("2006-01-02 15:04:05"),
        )
        if dbErr != nil {
            log.Printf("[ERROR] 记录退款失败信息失败: %v", dbErr)
        }
        return
    }
    
    // 记录退款成功
    log.Printf("[INFO] 微信退款请求成功: %+v, HTTP状态码: %d", resp, result.Response.StatusCode)
    
    // 保存退款记录
    _, err = db.Exec(
        `INSERT INTO Refunds 
        (OutRefundNo, TransactionID, OutTradeNo, Amount, Reason, Status, CreateTime) 
        VALUES (?, ?, ?, ?, ?, ?, ?)`,
        refundNo,
        transactionId,
        outTradeNo,
        amount,
        reason,
        "processing", // 初始状态为处理中
        time.Now().Format("2006-01-02 15:04:05"),
    )
    if err != nil {
        log.Printf("[ERROR] 保存退款记录失败: %v", err)
    }
}
// 根据OpenID获取用户信息
func getUserInfoByOpenID(openID string) (map[string]string, error) {
    // 从users表中获取wechatname和avatar
    var wechatname, avatarpath string
    
    err := db.QueryRow("SELECT wechatname, Avatarpath FROM users WHERE openid = ?", openID).Scan(&wechatname, &avatarpath)
    if err != nil {
        if err == sql.ErrNoRows {
            return nil, fmt.Errorf("未找到绑定该OpenID的用户")
        }
        return nil, fmt.Errorf("获取用户信息失败: %v", err)
    }
    
    return map[string]string{
        "name": wechatname,
        "avatarUrl": avatarpath,
    }, nil
}
func generateQRCode(c *gin.Context) {
	log.Printf("[INFO] 收到请求: POST /api/wxacode/unlimited | IP: %s", c.ClientIP())

	// 解析请求
	var req QRCodeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("[ERROR] 解析小程序码请求失败: %v", err)
		c.JSON(http.StatusBadRequest, QRCodeResponse{
			Code:    1,
			Message: "请求参数错误: " + err.Error(),
		})
		return
	}

	log.Printf("[INFO] 收到小程序码生成请求: GuaranteeID=%s, Scene=%s, Page=%s", 
		req.GuaranteeID, req.Scene, req.Page)

	// 验证参数
	if len(req.Scene) > 32 {
		log.Printf("[ERROR] Scene参数长度超过32个字符: %s", req.Scene)
		c.JSON(http.StatusBadRequest, QRCodeResponse{
			Code:    2,
			Message: "scene参数长度不能超过32个字符",
		})
		return
	}

	// 设置默认页面（如果未提供）
	if req.Page == "" {
		req.Page = "pages/index/index"
	}

	// 生成文件名（MD5哈希）
	sceneHash := md5.Sum([]byte(req.Scene + req.Page))
	filename := hex.EncodeToString(sceneHash[:]) + ".jpg"
	filePath := filepath.Join("static/qrcodes", filename)
	fileURL := fmt.Sprintf("/static/qrcodes/%s", filename)

	// 检查缓存是否存在
	if _, err := os.Stat(filePath); err == nil {
		log.Printf("[INFO] 使用缓存的小程序码: %s", filePath)
		c.JSON(http.StatusOK, QRCodeResponse{
			Code:     0,
			Message:  "成功获取小程序码",
			ImageURL: fileURL,
		})
		return
	}

	// 获取小程序access_token - 直接调用不缓存
	token, err := getMiniAccessToken()
	if err != nil {
		log.Printf("[ERROR] 获取access_token失败: %v", err)
		c.JSON(http.StatusInternalServerError, QRCodeResponse{
			Code:    3,
			Message: "获取微信access_token失败: " + err.Error(),
		})
		return
	}

    wxaParams := map[string]interface{}{
        "scene":      req.Scene,
        "page":       req.Page,
        "width":      430,
        "auto_color": false,
        "line_color": map[string]int{"r": 0, "g": 0, "b": 0},
        "is_hyaline": false,
        "env_version": "develop",  // 使用体验版
        "check_path": false,     // 不检查页面路径是否存在
    }

	// 请求微信API
	wxaURL := fmt.Sprintf("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", token)
	wxaParamsJSON, _ := json.Marshal(wxaParams)
	
	resp, err := http.Post(wxaURL, "application/json", bytes.NewBuffer(wxaParamsJSON))
	if err != nil {
		log.Printf("[ERROR] 请求微信小程序码API失败: %v", err)
		c.JSON(http.StatusInternalServerError, QRCodeResponse{
			Code:    4,
			Message: "请求微信API失败: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("[ERROR] 读取微信API响应失败: %v", err)
		c.JSON(http.StatusInternalServerError, QRCodeResponse{
			Code:    5,
			Message: "读取微信API响应失败: " + err.Error(),
		})
		return
	}

	// 检查是否返回错误信息（JSON格式）
	var errResp map[string]interface{}
	if err := json.Unmarshal(body, &errResp); err == nil {
		if errcode, ok := errResp["errcode"].(float64); ok && errcode != 0 {
			errmsg := errResp["errmsg"].(string)
			log.Printf("[ERROR] 微信API返回错误: errcode=%v, errmsg=%s", errcode, errmsg)
			c.JSON(http.StatusInternalServerError, QRCodeResponse{
				Code:    6,
				Message: fmt.Sprintf("微信API返回错误: %s", errmsg),
			})
			return
		}
	}

	// 保存图片文件
	if err := os.WriteFile(filePath, body, 0644); err != nil {
		log.Printf("[ERROR] 保存小程序码文件失败: %v", err)
		c.JSON(http.StatusInternalServerError, QRCodeResponse{
			Code:    7,
			Message: "保存小程序码文件失败: " + err.Error(),
		})
		return
	}

	log.Printf("[INFO] 成功生成小程序码: %s", filePath)

	// 返回结果
	c.JSON(http.StatusOK, QRCodeResponse{
		Code:     0,
		Message:  "成功生成小程序码",
		ImageURL: fileURL,
	})
}
func sendContactCard(srcUserName, desUserName string) {
    // 发送名片请求
    requestBody := map[string]interface{}{
        "api": 2212,
        "data": map[string]interface{}{
            "srcUserName": srcUserName,  // 要发送的微信ID
            "desUserName": desUserName,  // 接收者的微信ID
            "type": 0,
        },
    }
    
    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        log.Printf("序列化请求数据失败: %v", err)
        return
    }
    
    resp, err := http.Post("http://8.138.151.175:12590", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        log.Printf("发送 POST 请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    if resp.StatusCode != http.StatusOK {
        log.Printf("POST 请求返回错误状态: %d", resp.StatusCode)
        return
    }
    
    fmt.Printf("POST 请求成功，向 [%s] 发送 [%s] 的名片完成\n", desUserName, srcUserName)
}
// 拉黑API
func addToBlacklist(c *gin.Context) {
    var req struct {
        Nickname string `json:"nickname" binding:"required"`
        Code     string `json:"code" binding:"required"`
    }
    
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
        return
    }

    // 获取OpenID
    openid, err := getOpenIDFromCode(req.Code)
    if err != nil {
        log.Printf("[ERROR] 获取OpenID失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "success": false,
            "message": "获取用户信息失败",
        })
        return
    }

    // 从 friends 表中查询 userName，优先选择以 wxid 开头的
    var username string
    err = db.QueryRow(`
        SELECT userName 
        FROM friends 
        WHERE nickName = ? 
        ORDER BY 
            CASE 
                WHEN userName LIKE 'wxid%' THEN 0
                ELSE 1
            END,
            id ASC
        LIMIT 1
    `, req.Nickname).Scan(&username)
    
    if err != nil {
        log.Printf("[ERROR] 查询用户名失败: %v", err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "success": false,
            "message": "未找到对应用户",
        })
        return
    }

    // 插入黑名单记录
    _, err = db.Exec("INSERT INTO blacklist (username, openid) VALUES (?, ?)", 
        username, openid)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "添加黑名单失败"})
        return
    }

    c.JSON(http.StatusOK, gin.H{"success": true, "message": "已成功加入黑名单"})
}

// 查询黑名单API也需要相应修改
func getBlacklist(c *gin.Context) {
    rows, err := db.Query("SELECT username, openid, created_at FROM blacklist WHERE is_active = 1")
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "查询黑名单失败"})
        return
    }
    defer rows.Close()

    var blacklist []map[string]interface{}
    for rows.Next() {
        var username, openid, createdAt string
        if err := rows.Scan(&username, &openid, &createdAt); err != nil {
            continue
        }
        blacklist = append(blacklist, map[string]interface{}{
            "username":   username,
            "openid":     openid,
            "created_at": createdAt,
        })
    }

    c.JSON(http.StatusOK, gin.H{"success": true, "data": blacklist})
}
// 计算所有玩家升级所需的总价格
func calculateTotalPrice(db *sql.DB, orderType string, targetRanks []string, orders []string) (float64, error) {
    var totalPrice float64 = 0
    
    // 获取第一个玩家的升级级数
    if len(targetRanks) == 0 || len(orders) == 0 {
        return 0, fmt.Errorf("目标段位或订单不能为空")
    }
    
    // 获取所有段位与价格
    var rankPrices [][]string
    rows, err := db.Query("SELECT Rank, Price, RankOrder FROM RankPrices ORDER BY RankOrder")
    if err != nil {
        return 0, fmt.Errorf("获取段位价格失败: %v", err)
    }
    defer rows.Close()
    
    rankOrderMap := make(map[string]int)
    rankPriceMap := make(map[string]float64)
    
    for rows.Next() {
        var rank string
        var price float64
        var rankOrder int
        if err := rows.Scan(&rank, &price, &rankOrder); err != nil {
            return 0, fmt.Errorf("读取段位价格失败: %v", err)
        }
        rankOrderMap[rank] = rankOrder
        rankPriceMap[rank] = price
        rankPrices = append(rankPrices, []string{rank, fmt.Sprintf("%.2f", price)})
    }
    
    // 按段位名称长度降序排序，以便正确匹配含有段位名称的字符串
    sort.Slice(rankPrices, func(i, j int) bool {
        return len(rankPrices[i][0]) > len(rankPrices[j][0])
    })
    
    // 从第一个订单中直接提取初始段位，不依赖于逗号分隔
    initialOrder := orders[0]
    var initialRankMatched string
    
    // 尝试从订单文本中匹配段位
    for _, rankPrice := range rankPrices {
        if strings.Contains(initialOrder, rankPrice[0]) {
            initialRankMatched = rankPrice[0]
            break
        }
    }
    
    if initialRankMatched == "" {
        return 0, fmt.Errorf("无法从订单中提取段位: %s", initialOrder)
    }
    
    targetRank := targetRanks[0]
    
    // 获取初始段位和目标段位的序号
    initialRankOrder, ok := rankOrderMap[initialRankMatched]
    if !ok {
        return 0, fmt.Errorf("找不到段位的序号: %s", initialRankMatched)
    }
    
    targetRankOrder, ok := rankOrderMap[targetRank]
    if !ok {
        return 0, fmt.Errorf("找不到段位的序号: %s", targetRank)
    }
    
    if targetRankOrder <= initialRankOrder {
        return 0, fmt.Errorf("目标段位必须高于初始段位")
    }
    
    // 计算升级级数
    upgradeCount := targetRankOrder - initialRankOrder
    
    // 为每个玩家计算价格
    for _, order := range orders {
        // 从订单文本中直接提取段位，不依赖于逗号分隔
        var currentRankMatched string
        for _, rankPrice := range rankPrices {
            if strings.Contains(order, rankPrice[0]) {
                currentRankMatched = rankPrice[0]
                break
            }
        }
        
        if currentRankMatched == "" {
            return 0, fmt.Errorf("无法从订单中提取段位: %s", order)
        }
        
        // 获取当前段位的序号
        currentRankOrder, ok := rankOrderMap[currentRankMatched]
        if !ok {
            return 0, fmt.Errorf("找不到段位的序号: %s", currentRankMatched)
        }
        
        // 计算目标段位序号
        targetRankOrderForPlayer := currentRankOrder + upgradeCount
        
        // 如果计算出的目标段位超出最高段位，则截至到最高段位
        maxRankOrder := 0
        for _, order := range rankOrderMap {
            if order > maxRankOrder {
                maxRankOrder = order
            }
        }
        
        if targetRankOrderForPlayer > maxRankOrder {
            targetRankOrderForPlayer = maxRankOrder
        }
        
        // 计算从当前段位到目标段位所有级别的价格总和
        var playerPrice float64
        for j := currentRankOrder; j < targetRankOrderForPlayer; j++ {
            // 查找RankOrder为j的段位
            var rankWithOrderJ string
            for rank, order := range rankOrderMap {
                if order == j {
                    rankWithOrderJ = rank
                    break
                }
            }
            
            if rankWithOrderJ == "" {
                continue // 找不到对应的段位，跳过
            }
            
            price, ok := rankPriceMap[rankWithOrderJ]
            if !ok {
                continue // 找不到对应的价格，跳过
            }
            
            playerPrice += price
        }
        
        // 如果是代打类型，只收取一半价格
        if orderType == "代打" {
            playerPrice = playerPrice / 2
        }
        
        totalPrice += playerPrice
    }
    
    return totalPrice, nil
}
